@biza-gov/center-sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,36 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0 (beta)
4
+
5
+ - `environment: 'uat' | 'production'` (หรือ env `GOVCENTER_ENV`) เลือกที่อยู่ API ให้เอง: UAT `https://uat-api-auth.govcenter.co`, production `https://api-auth.govcenter.co` · `baseUrl` / `GOVCENTER_API_URL` ยังใช้ก่อน · ค่าอื่นจะ throw
6
+ - `GOVCENTER_API_URLS`, type `GovCenterEnvironment`; `getConfig().environment`
7
+ - DevKit: โหลดจาก `https://uat-auth.govcenter.co/sdk/v1/govcenter_devkit.js` แล้ว login และฝังแผนที่บน UAT เอง (ค่าเริ่มต้นของ `authUrl` = เว็บ login ของ GovCenter ที่โหลด script มา; สำเนาบนโดเมนอื่นยังใช้ production) · `govcenter.getAuthUrl()`, `govcenter.AUTH_URLS`
8
+ - คู่มือเชื่อมบน UAT: [UAT.md](../UAT.md)
9
+
10
+ ## 0.3.0 (beta)
11
+
12
+ - type ตาม Swagger ล่าสุด: 48 path, 50 operation (เดิม 39 / 41)
13
+ - ใหม่: `/e-services/profiles/:userId`, `/e-services/profiles/:userId/consents`, `/e-services/residences` (แบ่งหน้า), `/e-services/residences/by-house-code/:houseCode`, `/e-services/municipalities/:id`, `/org-units`, `/staff`, `/master-data/municipalities/nearby`
14
+ - `/e-services/sso/verify-code`: `user.positions`, `user.primaryMunicipalityId`
15
+ - **เปลี่ยนแบบไม่เข้ากันกับรุ่นเก่า:** `MunicipalityRole` เหลือ `ADMIN` | `MEMBER` (เลิก `OWNER`, `OPERATOR`, `VIEWER`)
16
+ - export type ที่ใช้บ่อย: `SsoVerifyResponse`, `SsoUser`, `SsoMembership`, `MunicipalityRole`, `SsoPosition`, `EServiceProfile`, `EServiceProfileConsent`, `EServiceResidencePage`, `EServiceResidenceSummary`, `EServiceResidenceDetail`, `EServiceMunicipality`, `EServiceOrgUnit`, `EServiceStaff`, `NearbyMunicipality`
17
+ - `GovCenterApiCode`: code ที่ GovCenter ส่งมาใน error (`CONSENT_REQUIRED`, `CALLBACK_NOT_ALLOWED`, `HOUSE_NOT_FOUND` ฯลฯ)
18
+ - README: ตัวอย่าง Core 2/4/11, ข้อมูลตำแหน่งจาก verify-code, สิ่งที่ต้องรู้เรื่อง 2FA ความยินยอม และ callback
19
+
20
+ ## 0.2.0 (beta)
21
+
22
+ - `serviceCode` (หรือ env `E_SERVICE_CODE`) ส่งเป็น `x-e-service-code` คู่กับ `x-api-key`; `getConfig().serviceCode`
23
+ - Script หน้าเว็บ `govcenter_devkit.js` (`window.govcenter`, v1): login, callback, session, ฝังแผนที่ · ไม่รับ API key · `npm run test:script`
24
+ - ชื่อแพ็กเกจใหม่ `@govcenter/sdk` (เดิม `gov-center-sdk` ไม่เคย publish)
25
+ - base URL เริ่มต้น `http://localhost:4001` (ไม่มี `/v1`)
26
+ - retry: GET เมื่อ 429/502/503/504, timeout, เน็ตหลุด; POST/PATCH/DELETE เฉพาะเมื่อมี `idempotencyKey`; สูงสุด 2 ครั้ง; timeout 10 วินาที
27
+ - ส่ง `x-api-key` เฉพาะ `/e-services/*`; บังคับ HTTPS ยกเว้น localhost; throw เมื่อสร้างในหน้าเว็บ
28
+ - `getConfig()` ไม่คืน key / secret
29
+ - `GovCenterError.code` ตามสถานะ HTTP, `requiredScope` (อ่านจากข้อความ "Missing e-service scope" ได้), `retryAfter`
30
+ - `@govcenter/sdk/testing`: `createGovCenterMock`, `mockResponse`
31
+ - ทดสอบกับ GovCenter ในเครื่อง: `npm run test:local`
32
+ - type ตาม path จาก Swagger ของ GovCenter (`npm run gen:types`): 39 path, 41 operation ของ `/e-services/*` และ `/master-data/*`; path ที่ไม่รู้จักใช้ `gc.request()`
33
+
34
+ ## 0.1.0
35
+
36
+ - `createGovCenterClient` + `get/post/patch/delete`, params, query array, retry, `GovCenterError` (ในเครื่อง ไม่ได้ publish)
package/README.md CHANGED
@@ -1,3 +1,209 @@
1
- # Temporary Holding Version
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.
1
+ # @biza-gov/center-sdk
2
+
3
+ SDK สำหรับ **backend ของ e-service** ใช้เรียก API ของ GovCenter (Core 1–11) เปลี่ยนแค่ path ก็ได้ข้อมูลของ Core นั้น
4
+
5
+ > ใช้ฝั่ง server เท่านั้น ถ้าถูกสร้างในหน้าเว็บ (browser) จะ throw ทันที เพราะ API key จะหลุดไปถึงผู้ใช้ทุกคน
6
+
7
+ ## ทำอะไรให้
8
+
9
+ - **4 คำสั่ง ทุก Core:** `gc.get`, `gc.post`, `gc.patch`, `gc.delete`
10
+ - **type ตาม path (สร้างจาก Swagger ของ GovCenter):** พิมพ์ path ผิด, ใช้ method ผิด, ลืม `params`, ใส่ query key ผิดหรือค่า enum ผิด, ลืม `body` = editor แจ้งทันที · ผลลัพธ์มี type เมื่อ GovCenter ระบุไว้ใน Swagger (ที่เหลือเป็น `unknown`)
11
+ - **`gc.request(method, path)`:** เรียก path ที่ใหม่กว่า SDK รุ่นที่ติดตั้งได้ทันที (ไม่มี type)
12
+ - **อ่านค่าจาก env เอง:** `GOVCENTER_API_URL` (หรือ `IAM_API_URL`), `E_SERVICE_API_KEY`, `E_SERVICE_CODE`
13
+ - **ส่ง `x-api-key` + `x-e-service-code` เฉพาะ `/e-services/*`:** path สาธารณะ เช่น `/master-data/*` ไม่ได้รับ key · GovCenter ปฏิเสธ code ที่ไม่ตรงกับ key
14
+ - **บังคับ HTTPS:** ยกเว้น `localhost` / `127.0.0.1`
15
+ - **แทนค่าใน path:** `/e-services/residences/:id` + `params` (ลืมใส่ = throw ก่อนส่ง)
16
+ - **query แบบ array:** `layers: ['home', 'stations']` → `layers=home,stations`
17
+ - **retry ที่ปลอดภัย:** GET retry เมื่อเจอ 429/502/503/504, timeout หรือเน็ตหลุด สูงสุด 2 ครั้ง (รอตาม `Retry-After`); POST/PATCH/DELETE retry **เฉพาะเมื่อมี `idempotencyKey`** จึงไม่ส่งแจ้งเตือนซ้ำ
18
+ - **timeout:** 10 วินาที ปรับได้ทั้ง client และราย request
19
+ - **`GovCenterError`:** `status`, `code`, `requiredScope`, `retryAfter`, `requestId`
20
+ - **`x-request-id`:** ทุก request ใช้ค้น log ร่วมกับทีม GovCenter
21
+ - **ชุดทดสอบ:** `@biza-gov/center-sdk/testing` จำลอง GovCenter โดยไม่ต้องรันระบบจริง
22
+ - **ไม่มี dependency:** ใช้ `fetch` ของ Node 20+
23
+
24
+ ## ติดตั้ง
25
+
26
+ ```bash
27
+ npm install @biza-gov/center-sdk
28
+ ```
29
+
30
+ `.env` ของ backend:
31
+
32
+ ```env
33
+ GOVCENTER_ENV=uat # uat | production (ไม่ต้องใส่ URL)
34
+ # หรือ GOVCENTER_API_URL=https://api-auth.govcenter.co # UAT: https://uat-api-auth.govcenter.co · ในเครื่อง: http://localhost:4001
35
+ E_SERVICE_API_KEY=<key ของ e-service>
36
+ E_SERVICE_CODE=<code ของ e-service เช่น gov-safecity>
37
+ ```
38
+
39
+ ```ts
40
+ // src/govcenter.ts
41
+ import { createGovCenterClient } from '@biza-gov/center-sdk';
42
+
43
+ export const gc = createGovCenterClient(); // อ่านค่าจาก env เอง
44
+ ```
45
+
46
+ ## Endpoint ที่ใหม่กว่า SDK
47
+
48
+ ```ts
49
+ // GovCenter เปิด endpoint ใหม่แล้ว แต่ SDK รุ่นที่ติดตั้งยังไม่รู้จัก
50
+ const stats = await gc.request<MyStats>('GET', '/e-services/some-new/endpoint', { query: { from, to } });
51
+ ```
52
+
53
+ ตั้งแต่ 0.3.0 ผลลัพธ์ของ Core 1–5, 8–11 และ `/e-services/me` มี type แล้ว (48 path) ส่วนที่ Swagger ยังไม่ระบุชนิดจะเป็น `unknown` ให้ระบุเองด้วย `as` จนกว่า GovCenter จะเพิ่ม `@ApiOkResponse`:
54
+
55
+ ```ts
56
+ const catalog = (await gc.get('/e-services/gis/catalog')) as GisCatalog;
57
+ ```
58
+
59
+ ## ตัวอย่างแต่ละ Core
60
+
61
+ ```ts
62
+ // Core 1 · แลก SSO code เป็นข้อมูลผู้ใช้ (ใน POST /auth/sso-callback ของ e-service)
63
+ const session = await gc.post('/e-services/sso/verify-code', { body: { code } });
64
+
65
+ // Core 3 · จังหวัด อำเภอ ตำบล (สาธารณะ ไม่ส่ง key)
66
+ const geography = await gc.get('/master-data/geography');
67
+ const districts = await gc.get('/master-data/provinces/:id/districts', { params: { id: provinceId } });
68
+
69
+ // Core 4 · เทศบาลในจังหวัด และพื้นที่รับผิดชอบ
70
+ const municipalities = await gc.get('/master-data/municipalities/search', { query: { provinceId } });
71
+ const areas = await gc.get('/master-data/municipalities/areas', { query: { ids: [municipalityId] } });
72
+
73
+ // Core 5 · แผนที่: รายการ layer และข้อมูลหลาย Core ในครั้งเดียว
74
+ const catalog = await gc.get('/e-services/gis/catalog');
75
+ const mapData = await gc.get('/e-services/gis/map-data', { query: { layers: ['stations', 'municipality'], municipalityId } });
76
+
77
+ // Core 8 · ส่งแจ้งเตือน (idempotencyKey กันส่งซ้ำ และทำให้ retry ได้)
78
+ const sent = await gc.post('/e-services/notifications', {
79
+ body: { title: 'แจ้งเตือนน้ำท่วมฉับพลัน', message: 'โปรดเคลื่อนย้ายสิ่งของขึ้นที่สูง', audience: { type: 'municipality' } },
80
+ idempotencyKey: `${incident.reference}-residents`,
81
+ });
82
+ const history = await gc.get('/e-services/notifications/search', { query: { reference: incident.reference } });
83
+
84
+ // Core 9 · สถิติความพึงพอใจของ e-service ตัวเอง
85
+ const stats = await gc.get('/e-services/evaluations/stats');
86
+
87
+ // Core 10 · สถานี
88
+ const stations = await gc.get('/e-services/stations/search');
89
+
90
+ // Core 11 · บ้าน (ต้องมี scope)
91
+ const home = await gc.get('/e-services/residences/:id', { params: { id }, query: { include: 'members' } });
92
+ const page = await gc.get('/e-services/residences', { query: { municipalityId, page: '1' } });
93
+ const byCode = await gc.get('/e-services/residences/by-house-code/:houseCode', { params: { houseCode: '38301234567' } });
94
+
95
+ // Core 2 · ข้อมูลส่วนบุคคล (scope profile:* + ความยินยอมของผู้ใช้; ช่องที่ไม่ได้รับอนุญาตเป็น null)
96
+ const profile = await gc.get('/e-services/profiles/:userId', { params: { userId }, query: { fields: 'firstName,lastName,mobilePhone' } });
97
+
98
+ // Core 4 · โครงสร้างเทศบาลและเจ้าหน้าที่ (scope org:read)
99
+ const units = await gc.get('/e-services/municipalities/:id/org-units', { params: { id: municipalityId } });
100
+ const staff = await gc.get('/e-services/municipalities/:id/staff', { params: { id: municipalityId } });
101
+ ```
102
+
103
+ ### ข้อมูลผู้ใช้จาก verify-code (0.3.0)
104
+
105
+ ```ts
106
+ import type { SsoVerifyResponse, SsoPosition } from '@biza-gov/center-sdk';
107
+
108
+ const { user } = (await gc.post('/e-services/sso/verify-code', { body: { code } })) as SsoVerifyResponse;
109
+ user.memberships[0]?.role; // 'ADMIN' | 'MEMBER' (OWNER / OPERATOR / VIEWER เลิกใช้แล้ว)
110
+ user.primaryMunicipalityId; // เทศบาลหลักของผู้ใช้
111
+ const seats: SsoPosition[] = user.positions; // ที่นั่งที่มีผู้ดำรง: branch, level, position, orgUnit, duties
112
+ ```
113
+
114
+ - หน้าที่ของเจ้าหน้าที่มาจาก `positions` ไม่ได้มาจาก role · ที่นั่งสภา (`LEGISLATIVE`) มีแค่ `branch` กับ `level`
115
+ - `positions` มีเฉพาะเทศบาลที่ e-service ผูกไว้ (ยกเว้น e-service แบบ shared)
116
+
117
+ ### การเข้าสู่ระบบที่ e-service ต้องรู้
118
+
119
+ - ผู้ใช้ที่เปิดยืนยันตัวตนสองขั้นจะกรอกรหัสที่ GovCenter ก่อน e-service ไม่ต้องทำอะไรเพิ่ม
120
+ - e-service ที่ได้ scope ข้อมูลส่วนบุคคล: GovCenter ขอความยินยอมจากผู้ใช้ก่อนออก SSO code (`CONSENT_REQUIRED`) แล้วพากลับมาเอง
121
+ - callback ต้องอยู่ใน `baseUrl` / `allowedOrigins` ที่ลงทะเบียนไว้ (https) ไม่งั้นได้ `CALLBACK_NOT_ALLOWED`
122
+ - e-service ที่ทำหน้า login ด้วยรหัสผ่านเอง (proxy `/auth/login`) ต้องรองรับคำตอบ `{ requires2fa, challengeToken }`
123
+
124
+ ## จัดการ error
125
+
126
+ ```ts
127
+ import { GovCenterError } from '@biza-gov/center-sdk';
128
+
129
+ try {
130
+ await gc.get('/e-services/residences/search', { query: { q } });
131
+ } catch (e) {
132
+ if (e instanceof GovCenterError && e.code === 'MISSING_SCOPE') {
133
+ logger.warn(`ต้องขอ scope ${e.requiredScope} จาก super admin`);
134
+ }
135
+ throw e;
136
+ }
137
+ ```
138
+
139
+ | `code` | HTTP | ความหมาย |
140
+ | --- | --- | --- |
141
+ | `VALIDATION` | 400 | body / query ผิด ดู `message` |
142
+ | `UNAUTHORIZED` | 401 | ไม่มี key หรือ key ผิด |
143
+ | `FORBIDDEN` | 403 | e-service ถูกปิด หรือ code SSO ใช้ไม่ได้ |
144
+ | `MISSING_SCOPE` | 403 | ไม่มีสิทธิ์ ดู `requiredScope` |
145
+ | `NOT_FOUND` | 404 | ไม่พบข้อมูล หรือพิมพ์ path ผิด |
146
+ | `CONFLICT` | 409 | ข้อมูลซ้ำ |
147
+ | `RATE_LIMITED` | 429 | เรียกถี่เกิน ดู `retryAfter` (วินาที) |
148
+ | `INTERNAL_ERROR` / `UPSTREAM` | 5xx | GovCenter ขัดข้อง (`INTERNAL_ERROR` เมื่อ GovCenter ส่ง code มา) |
149
+ | `TIMEOUT`, `NETWORK` | - | ต่อ GovCenter ไม่ได้ |
150
+
151
+ GovCenter ส่ง `code` เฉพาะเรื่องมาด้วย (type `GovCenterApiCode`): `MUNICIPALITY_NOT_BOUND`, `MUNICIPALITY_NOT_FOUND`, `HOUSE_NOT_FOUND`, `HOUSE_CODE_LOOKUP_LIMIT`, `CONSENT_REQUIRED`, `CALLBACK_NOT_ALLOWED`, `TOTP_REQUIRED`, `MFA_REQUIRED` · อาจมี code ใหม่เพิ่ม ให้มีกรณี default เสมอ
152
+
153
+ ## ทดสอบโค้ดของ e-service
154
+
155
+ ```ts
156
+ import { createGovCenterMock, mockResponse } from '@biza-gov/center-sdk/testing';
157
+
158
+ const gc = createGovCenterMock({
159
+ 'GET /e-services/gis/catalog': { layers: [] },
160
+ 'GET /e-services/residences/:id': (req) => ({ id: req.params.id }),
161
+ 'POST /e-services/notifications': mockResponse(403, { message: 'Missing e-service scope: notification:send' }),
162
+ });
163
+ // path ที่ไม่ได้ mock ได้ 404 จึงเห็นทันทีถ้าพิมพ์ path ผิด; gc.calls เก็บทุก request
164
+ ```
165
+
166
+ ## Script สำหรับหน้าเว็บ (ไม่ต้องติดตั้ง)
167
+
168
+ หน้าเว็บของ e-Service ใช้ script ตัวนี้ได้เลย ไม่ต้องใช้ npm:
169
+
170
+ ```html
171
+ <script src="https://auth.govcenter.co/sdk/v1/govcenter_devkit.js"></script>
172
+ <!-- UAT: https://uat-auth.govcenter.co/sdk/v1/govcenter_devkit.js — login และแผนที่จะใช้ UAT ให้เอง -->
173
+ <script>
174
+ govcenter.init({
175
+ serviceCode: 'gov-safecity',
176
+ callbackUrl: 'https://safecity.example.go.th/auth/callback',
177
+ apiBaseUrl: 'https://api.safecity.example.go.th', // backend ของ e-Service เอง
178
+ });
179
+ </script>
180
+ ```
181
+
182
+ **script ไม่มี API key และไม่เรียกข้อมูล Core เอง** ใส่ `apiKey` แล้ว `init` จะ throw เพราะทุกคนที่เปิดหน้าเว็บอ่าน key ได้ ข้อมูลจาก GovCenter ให้ backend ของ e-Service เรียกด้วย `x-api-key` + `x-e-service-code` (SDK ข้างบน หรือ REST ตรง)
183
+
184
+ | คำสั่ง | ทำอะไร |
185
+ | --- | --- |
186
+ | `govcenter.login()` / `getLoginUrl()` | ไปหน้า login กลาง พร้อม `state` กัน CSRF |
187
+ | `govcenter.handleCallback()` | ในหน้า `callbackUrl`: ตรวจ `state` แล้วส่ง `{ code }` ไป `apiBaseUrl` + `/auth/sso-callback` ให้ backend แลกกับ GovCenter |
188
+ | `govcenter.getCallbackParams()` | อ่าน `code`, `state`, `error` จาก URL ถ้าอยากส่งเอง |
189
+ | `govcenter.checkSession()` | ถาม backend (`/auth/me`) ว่ามี session แล้วหรือยัง |
190
+ | `govcenter.map.embed('#map', url)` | ฝังแผนที่กลาง `url` มาจาก backend (`POST /e-services/gis/map-sessions`) รับเฉพาะหน้าแผนที่ของ GovCenter |
191
+
192
+ ล็อกเวอร์ชันด้วย `integrity` (ค่าอยู่ใน `dist-script/govcenter_devkit.js.sri` หลัง build) และ `crossorigin="anonymous"` `v1` อัปเดตแบบไม่ทำให้ของเดิมพัง ถ้าเปลี่ยนแบบไม่เข้ากันจะออก `v2`
193
+
194
+ ## พัฒนา SDK
195
+
196
+ ```bash
197
+ npm install
198
+ npm test # build + unit test (fetch จำลอง)
199
+ npm run test:local # build + เรียก GovCenter ในเครื่องจริง (อ่านเท่านั้น ไม่สร้างหรือส่งอะไร)
200
+ npm run typecheck # รวมการตรวจว่า path ผิดต้อง error (__tests__/types.check.ts)
201
+ npm run gen:types # สร้าง type ใหม่จาก {GOVCENTER_API_URL}/api-json เมื่อ GovCenter เพิ่ม/แก้ endpoint
202
+ npm run test:script # build script หน้าเว็บ (dist-script/govcenter_devkit.js + .sri) แล้วทดสอบ
203
+ ```
204
+
205
+ ปล่อย script ใหม่: `npm run test:script` แล้วคัดลอก `dist-script/govcenter_devkit.js` ไปที่ `gov-auth-frontend/public/sdk/v1/` และ deploy หน้าเว็บ
206
+
207
+ `test:local` อ่าน URL และ key จาก env หรือจาก `govcenter-safecity/gov-safecity/api/.env` (เปลี่ยนไฟล์ได้ด้วย `GOVCENTER_ENV_FILE`) ไม่แสดงค่า key ถ้า GovCenter ไม่ได้รันจะข้ามเทสต์ทั้งหมด
208
+
209
+ แผนพัฒนาแบ่ง phase อยู่ใน [PLAN.md](PLAN.md) หัวข้อ 4
@@ -0,0 +1,260 @@
1
+ // src/error.ts
2
+ function codeForStatus(status, requiredScope) {
3
+ if (status === 400 || status === 422) return "VALIDATION";
4
+ if (status === 401) return "UNAUTHORIZED";
5
+ if (status === 403) return requiredScope ? "MISSING_SCOPE" : "FORBIDDEN";
6
+ if (status === 404) return "NOT_FOUND";
7
+ if (status === 409) return "CONFLICT";
8
+ if (status === 429) return "RATE_LIMITED";
9
+ if (status >= 500) return "UPSTREAM";
10
+ return "HTTP_ERROR";
11
+ }
12
+ var GovCenterError = class _GovCenterError extends Error {
13
+ status;
14
+ code;
15
+ requiredScope;
16
+ /** Seconds to wait before retrying, from the Retry-After header. */
17
+ retryAfter;
18
+ requestId;
19
+ details;
20
+ constructor(options) {
21
+ super(options.message);
22
+ this.name = "GovCenterError";
23
+ this.status = options.status;
24
+ this.code = options.code ?? codeForStatus(options.status, options.requiredScope);
25
+ this.requiredScope = options.requiredScope;
26
+ this.retryAfter = options.retryAfter;
27
+ this.requestId = options.requestId;
28
+ this.details = options.details;
29
+ Object.setPrototypeOf(this, _GovCenterError.prototype);
30
+ }
31
+ get isRateLimited() {
32
+ return this.status === 429;
33
+ }
34
+ get isUnauthorized() {
35
+ return this.status === 401;
36
+ }
37
+ get isForbidden() {
38
+ return this.status === 403;
39
+ }
40
+ get isNotFound() {
41
+ return this.status === 404;
42
+ }
43
+ get isServerError() {
44
+ return this.status >= 500;
45
+ }
46
+ };
47
+
48
+ // src/retry.ts
49
+ function isRetryableStatus(status) {
50
+ return status === 429 || status === 502 || status === 503 || status === 504;
51
+ }
52
+ async function wait(ms) {
53
+ return new Promise((resolve) => setTimeout(resolve, ms));
54
+ }
55
+ function parseRetryAfter(header) {
56
+ if (!header) return void 0;
57
+ const seconds = Number(header);
58
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds;
59
+ const date = Date.parse(header);
60
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
61
+ return void 0;
62
+ }
63
+ function calculateBackoff(attempt, baseDelayMs = 300, maxDelayMs = 5e3, retryAfterHeader) {
64
+ const retryAfter = parseRetryAfter(retryAfterHeader);
65
+ if (retryAfter !== void 0) {
66
+ return Math.min(retryAfter * 1e3, maxDelayMs);
67
+ }
68
+ const exp = Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
69
+ const jitter = exp * (0.8 + Math.random() * 0.4);
70
+ return Math.floor(jitter);
71
+ }
72
+
73
+ // src/client.ts
74
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
75
+ var GOVCENTER_API_URLS = Object.freeze({
76
+ production: "https://api-auth.govcenter.co",
77
+ uat: "https://uat-api-auth.govcenter.co"
78
+ });
79
+ function readEnvironment(value) {
80
+ if (!value) return null;
81
+ const name = value.trim().toLowerCase();
82
+ if (name === "prod") return "production";
83
+ if (name === "production" || name === "uat") return name;
84
+ throw new Error(`Unknown GovCenter environment "${value}": use "uat" or "production"`);
85
+ }
86
+ function generateRequestId() {
87
+ if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") {
88
+ return globalThis.crypto.randomUUID();
89
+ }
90
+ return `gc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;
91
+ }
92
+ function isBrowser() {
93
+ const g = globalThis;
94
+ return typeof g.window !== "undefined" && typeof g.document !== "undefined";
95
+ }
96
+ function needsApiKey(path) {
97
+ return path === "/e-services" || path.startsWith("/e-services/");
98
+ }
99
+ function errorMessage(body, fallback) {
100
+ const message = body?.message;
101
+ if (Array.isArray(message)) return message.join(", ");
102
+ if (typeof message === "string" && message) return message;
103
+ return fallback;
104
+ }
105
+ function createGovCenterClient(config = {}) {
106
+ if (isBrowser() && !config.dangerouslyAllowBrowser) {
107
+ throw new Error(
108
+ "gov-center-sdk runs on the server only: the API key would be visible to every visitor. Call your own backend from the browser instead."
109
+ );
110
+ }
111
+ const env = globalThis.process?.env ?? {};
112
+ const environment = readEnvironment(config.environment ?? env.GOVCENTER_ENV);
113
+ const baseUrl = (config.baseUrl || env.GOVCENTER_API_URL || env.IAM_API_URL || (environment ? GOVCENTER_API_URLS[environment] : "http://localhost:4001")).replace(/\/+$/, "");
114
+ const apiKey = config.apiKey ?? env.E_SERVICE_API_KEY ?? "";
115
+ const apiSecret = config.apiSecret ?? env.E_SERVICE_API_SECRET ?? "";
116
+ const serviceCode = (config.serviceCode ?? env.E_SERVICE_CODE ?? "").trim();
117
+ const timeoutMs = config.timeoutMs ?? 1e4;
118
+ const maxRetries = config.maxRetries ?? 2;
119
+ const customFetch = config.fetch || globalThis.fetch;
120
+ let parsedBase;
121
+ try {
122
+ parsedBase = new URL(baseUrl);
123
+ } catch {
124
+ throw new Error(`Invalid GovCenter baseUrl: ${baseUrl}`);
125
+ }
126
+ if (parsedBase.protocol !== "https:" && !(parsedBase.protocol === "http:" && LOCAL_HOSTS.has(parsedBase.hostname))) {
127
+ throw new Error(`GovCenter baseUrl must use https (http is allowed only for localhost): ${baseUrl}`);
128
+ }
129
+ if (typeof customFetch !== "function") {
130
+ throw new Error(
131
+ "Global fetch is not available in this environment. Please pass a custom fetch to createGovCenterClient({ fetch })."
132
+ );
133
+ }
134
+ function resolvePath(path, params) {
135
+ let resolved = path.startsWith("/") ? path : `/${path}`;
136
+ if (params) {
137
+ for (const [key, val] of Object.entries(params)) {
138
+ resolved = resolved.replace(new RegExp(`:${key}\\b`, "g"), encodeURIComponent(String(val)));
139
+ }
140
+ }
141
+ const missing = resolved.match(/\/:([A-Za-z_][A-Za-z0-9_]*)/);
142
+ if (missing) {
143
+ throw new Error(`Missing path parameter "${missing[1]}" for ${path}`);
144
+ }
145
+ if (baseUrl.endsWith("/v1") && (resolved === "/v1" || resolved.startsWith("/v1/"))) {
146
+ resolved = resolved.slice(3) || "/";
147
+ }
148
+ return resolved;
149
+ }
150
+ function buildUrl(resolvedPath, query) {
151
+ let url = `${baseUrl}${resolvedPath}`;
152
+ if (query) {
153
+ const searchParams = new URLSearchParams();
154
+ for (const [key, val] of Object.entries(query)) {
155
+ if (val === void 0 || val === null) continue;
156
+ searchParams.append(key, Array.isArray(val) ? val.join(",") : String(val));
157
+ }
158
+ const qs = searchParams.toString();
159
+ if (qs) url += (url.includes("?") ? "&" : "?") + qs;
160
+ }
161
+ return url;
162
+ }
163
+ async function executeRequest(method, path, options = {}) {
164
+ const resolvedPath = resolvePath(path, options.params);
165
+ const url = buildUrl(resolvedPath, options.query);
166
+ const requestId = generateRequestId();
167
+ const headers = {
168
+ Accept: "application/json",
169
+ "x-request-id": requestId,
170
+ ...options.headers
171
+ };
172
+ if (apiKey && needsApiKey(resolvedPath)) {
173
+ headers["x-api-key"] = apiKey;
174
+ if (serviceCode) headers["x-e-service-code"] = serviceCode;
175
+ }
176
+ if (options.idempotencyKey) {
177
+ headers["Idempotency-Key"] = options.idempotencyKey;
178
+ }
179
+ let requestBody;
180
+ if (options.body !== void 0 && options.body !== null) {
181
+ headers["Content-Type"] = "application/json";
182
+ requestBody = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
183
+ }
184
+ const currentTimeout = options.timeoutMs ?? timeoutMs;
185
+ const canRetry = method === "GET" || Boolean(options.idempotencyKey);
186
+ let attempt = 0;
187
+ while (true) {
188
+ const controller = new AbortController();
189
+ const timer = setTimeout(() => controller.abort(), currentTimeout);
190
+ let response;
191
+ try {
192
+ response = await customFetch(url, { method, headers, body: requestBody, signal: controller.signal });
193
+ } catch (err) {
194
+ clearTimeout(timer);
195
+ const isAbort = err?.name === "AbortError";
196
+ if (canRetry && attempt < maxRetries) {
197
+ await wait(calculateBackoff(attempt));
198
+ attempt++;
199
+ continue;
200
+ }
201
+ throw new GovCenterError({
202
+ status: 0,
203
+ code: isAbort ? "TIMEOUT" : "NETWORK",
204
+ message: isAbort ? `GovCenter request timeout after ${currentTimeout}ms` : err?.message || "Network request failed",
205
+ requestId
206
+ });
207
+ }
208
+ clearTimeout(timer);
209
+ if (response.ok) {
210
+ if (response.status === 204) return void 0;
211
+ const text = await response.text();
212
+ return text ? JSON.parse(text) : void 0;
213
+ }
214
+ const retryAfterHeader = response.headers?.get?.("Retry-After") ?? null;
215
+ if (canRetry && isRetryableStatus(response.status) && attempt < maxRetries) {
216
+ await wait(calculateBackoff(attempt, 300, 5e3, retryAfterHeader));
217
+ attempt++;
218
+ continue;
219
+ }
220
+ let errorBody = void 0;
221
+ try {
222
+ const text = await response.text();
223
+ errorBody = text ? JSON.parse(text) : void 0;
224
+ } catch {
225
+ errorBody = void 0;
226
+ }
227
+ const body = errorBody ?? {};
228
+ const message = errorMessage(errorBody, response.statusText || `Request failed with status ${response.status}`);
229
+ const scopeInMessage = response.status === 403 ? message.match(/missing [\w-]* ?scope:\s*([\w:.-]+)/i)?.[1] : void 0;
230
+ throw new GovCenterError({
231
+ status: response.status,
232
+ message,
233
+ code: typeof body.code === "string" ? body.code : void 0,
234
+ requiredScope: typeof body.requiredScope === "string" ? body.requiredScope : scopeInMessage,
235
+ retryAfter: parseRetryAfter(retryAfterHeader),
236
+ requestId: response.headers?.get?.("x-request-id") || requestId,
237
+ details: errorBody
238
+ });
239
+ }
240
+ }
241
+ const call = (method) => (path, options) => executeRequest(method, path, options);
242
+ return {
243
+ get: call("GET"),
244
+ post: call("POST"),
245
+ patch: call("PATCH"),
246
+ delete: call("DELETE"),
247
+ request: (method, path, options) => executeRequest(method, path, options),
248
+ getConfig: () => Object.freeze({ baseUrl, environment, timeoutMs, maxRetries, hasApiKey: Boolean(apiKey), hasApiSecret: Boolean(apiSecret), serviceCode })
249
+ };
250
+ }
251
+
252
+ export {
253
+ codeForStatus,
254
+ GovCenterError,
255
+ isRetryableStatus,
256
+ parseRetryAfter,
257
+ calculateBackoff,
258
+ GOVCENTER_API_URLS,
259
+ createGovCenterClient
260
+ };