@adobe/spacecat-shared-project-engine-client 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,263 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions
133
+ of this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
203
+
204
+ APACHE JACKRABBIT SUBCOMPONENTS
205
+
206
+ Apache Jackrabbit includes parts with separate copyright notices and license
207
+ terms. Your use of these subcomponents is subject to the terms and conditions
208
+ of the following licenses:
209
+
210
+ XPath 2.0/XQuery 1.0 Parser:
211
+ http://www.w3.org/2002/11/xquery-xpath-applets/xgrammar.zip
212
+
213
+ Copyright (C) 2002 World Wide Web Consortium, (Massachusetts Institute of
214
+ Technology, European Research Consortium for Informatics and Mathematics,
215
+ Keio University). All Rights Reserved.
216
+
217
+ This work is distributed under the W3C(R) Software License in the hope
218
+ that it will be useful, but WITHOUT ANY WARRANTY; without even the
219
+ implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
220
+
221
+ W3C(R) SOFTWARE NOTICE AND LICENSE
222
+ http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
223
+
224
+ This work (and included software, documentation such as READMEs, or
225
+ other related items) is being provided by the copyright holders under
226
+ the following license. By obtaining, using and/or copying this work,
227
+ you (the licensee) agree that you have read, understood, and will comply
228
+ with the following terms and conditions.
229
+
230
+ Permission to copy, modify, and distribute this software and its
231
+ documentation, with or without modification, for any purpose and
232
+ without fee or royalty is hereby granted, provided that you include
233
+ the following on ALL copies of the software and documentation or
234
+ portions thereof, including modifications:
235
+
236
+ 1. The full text of this NOTICE in a location viewable to users
237
+ of the redistributed or derivative work.
238
+
239
+ 2. Any pre-existing intellectual property disclaimers, notices,
240
+ or terms and conditions. If none exist, the W3C Software Short
241
+ Notice should be included (hypertext is preferred, text is
242
+ permitted) within the body of any redistributed or derivative code.
243
+
244
+ 3. Notice of any changes or modifications to the files, including
245
+ the date changes were made. (We recommend you provide URIs to the
246
+ location from which the code is derived.)
247
+
248
+ THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
249
+ HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
250
+ INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
251
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
252
+ DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
253
+ TRADEMARKS OR OTHER RIGHTS.
254
+
255
+ COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL
256
+ OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
257
+ DOCUMENTATION.
258
+
259
+ The name and trademarks of copyright holders may NOT be used in
260
+ advertising or publicity pertaining to the software without specific,
261
+ written prior permission. Title to copyright in this software and
262
+ any associated documentation will at all times remain with
263
+ copyright holders.
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # @adobe/spacecat-shared-project-engine-client
2
+
3
+ Typed integration with the Semrush **Project Engine API** (`/enterprise/projects/api`):
4
+
5
+ - generated **TypeScript** (`src/generated/types.ts`) and **Pydantic v2** (`python/serenity_project_engine/`) types,
6
+ - a thin **Project Engine client** (`openapi-fetch` over the generated `paths`) — IMS Bearer auth + idempotency-aware retries (see [Client](#client)),
7
+ - a generation-time **spec-correction overlay** (`spec/overlays/corrections.yaml`) that aligns the vendored swagger with the live API,
8
+ - a **Counterfact mock** for E2E tests and local dev (`npm run mock`); the stateful mock store lands in a follow-up (LLMO-5460).
9
+
10
+ > **Not here yet:** the IMS auth-handler move and the stateful mock store are
11
+ > tracked follow-ups (see LLMO-5461 / LLMO-5460).
12
+
13
+ This package follows the `spacecat-shared` convention: **JS + ESM**, JSDoc-typed source,
14
+ `mocha` + `chai` + `c8` for tests, and `@adobe/eslint-config-helix` for lint. The scaffold's
15
+ TypeScript surface is ported to JS + JSDoc; the generated `types.ts` is a **type artifact only**,
16
+ consumed by the client via JSDoc `import(...)` and by `openapi-fetch` at type-check time.
17
+
18
+ ## Client
19
+
20
+ ```js
21
+ import { createSerenityProjectEngineApiClient } from '@adobe/spacecat-shared-project-engine-client';
22
+
23
+ const client = createSerenityProjectEngineApiClient({
24
+ baseUrl: process.env.SEMRUSH_PROJECTS_BASE_URL, // origin only; the prefix is owned by the client
25
+ authToken: () => getImsToken(), // a static token or a (sync/async) per-request getter
26
+ });
27
+
28
+ const { data, error } = await client.GET('/v1/countries');
29
+ ```
30
+
31
+ - **Auth:** the caller's IMS JWT is forwarded verbatim as `Authorization: Bearer <token>`. The
32
+ live API authenticates on Bearer directly — Semrush accepts the IMS token and the client mints
33
+ or exchanges **nothing**. The token source resolves once per request, so the header always
34
+ reflects the current caller.
35
+ - **Base URL:** the client owns the fixed `/enterprise/projects/api` prefix; you pass only the
36
+ origin (any path/credentials are stripped). Non-`http(s)` base URLs fail fast at construction.
37
+ - **Retries:** `429` is retried for any method; `5xx`/network errors only for idempotent methods
38
+ (so a POST is never replayed). Backoff is exponential with jitter, honours `Retry-After`, and is
39
+ capped at 20s/attempt. Pass `onRetry` to observe the loop.
40
+ - **Shape:** this is a thin factory function rather than the `CLAUDE.md` "class + factory" client
41
+ pattern — the wrapper has no per-instance state or behaviour beyond what `openapi-fetch` already
42
+ provides, so a class would add ceremony without value. The typed surface IS the `openapi-fetch`
43
+ client.
44
+
45
+ ## Spec source
46
+
47
+ The spec is a **vendored file** — `spec/projectengine_swagger_public.yaml` — kept under
48
+ version control. Semrush only provides the file (no endpoint access in the near term), and
49
+ it's **Swagger 2.0** (no v3/v3.1 on offer). The vendored file is **never edited**; where it
50
+ diverges from the live API, a generation-time overlay corrects the converted artifact instead (see
51
+ [Spec corrections](#spec-corrections)). Refresh is **manual**: drop in the newer file, re-run
52
+ `npm run generate`, and review the diff. There is no automated drift detection while endpoint
53
+ access is restricted.
54
+
55
+ ## Pipeline
56
+
57
+ ```
58
+ spec/projectengine_swagger_public.yaml (vendored, Swagger 2.0)
59
+
60
+ ├── Counterfact ── reads v2 directly ──► mock (no conversion) [npm run mock]
61
+
62
+ └── swagger2openapi (v2 → 3.x) ──► build/openapi3.json
63
+
64
+ ├── apply-overlay (corrections) ──► build/openapi3.json (in place)
65
+
66
+ ├── openapi-typescript ──► src/generated/types.ts
67
+ └── datamodel-code-generator ──► python/serenity_project_engine/
68
+ ```
69
+
70
+ The v2 → 3.x conversion exists **only** to feed the type generators (`openapi-typescript`
71
+ is v3-only, and 3.x yields cleaner TS/Pydantic); the overlay then corrects that converted
72
+ artifact before the generators run (see [Spec corrections](#spec-corrections)). **Counterfact reads
73
+ the raw v2 file directly**, so the mock path never touches the converted artifact (and so does not
74
+ see the corrections — a known gap the stateful-mock follow-up addresses).
75
+
76
+ | Command | Does |
77
+ | --- | --- |
78
+ | `npm run spec:convert` | v2 → 3.x via `swagger2openapi --patch` → `build/openapi3.json` |
79
+ | `npm run spec:overlay` | apply `spec/overlays/corrections.yaml` to `build/openapi3.json` in place |
80
+ | `npm run generate:ts` | `openapi-typescript` → `src/generated/types.ts` |
81
+ | `npm run generate:pydantic` | `datamodel-code-generator` → `python/serenity_project_engine/` package |
82
+ | `npm run generate` | all of the above, in order |
83
+ | `npm run mock` | Counterfact mock on `:4010`, straight off the v2 spec |
84
+
85
+ `datamodel-code-generator` is a **Python** tool, not an npm dependency. Install it once on
86
+ your `PATH` before running `generate:pydantic`:
87
+
88
+ ```bash
89
+ pip install datamodel-code-generator
90
+ ```
91
+
92
+ ## Spec corrections
93
+
94
+ The vendored swagger diverges from the live API in three places. A small OpenAPI Overlay
95
+ (`spec/overlays/corrections.yaml`), applied to the converted OAS3 artifact at generation time by
96
+ `scripts/apply-overlay.mjs`, corrects them; the vendored `spec/projectengine_swagger_public.yaml`
97
+ is never touched.
98
+
99
+ - **CR1 — missing endpoint.** Adds `GET /v1/ai_models` (the live global model catalog), which is
100
+ absent from the upstream swagger.
101
+ - **CR2 — auth.** The spec models a required `Auth-Data-Jwt` header, but the live API authenticates
102
+ on `Authorization: Bearer <IMS>` only — Semrush accepts the IMS bearer directly. The overlay
103
+ removes `Auth-Data-Jwt` from every operation and adds an `imsBearer` security scheme.
104
+ - **CR3 — drafts.** Corrects the `GET /v2/workspaces/{id}/projects` description: it also returns
105
+ initial, never-yet-published draft projects, not only published ones.
106
+
107
+ Guard tests in `test/foundation.test.js` pin CR1 and CR2 against the generated surface, so a future
108
+ Semrush spec refresh that silently drops the overlay fails loudly instead of regressing the
109
+ generated types. `test/overlay.test.js` covers the overlay applier itself.
110
+
111
+ ## Committed vs generated
112
+
113
+ - **Committed:** the vendored spec (`spec/projectengine_swagger_public.yaml`).
114
+ - **Generated, committed in its own commit** and marked `linguist-generated` (see
115
+ `.gitattributes`) so it's collapsed in review and excluded from diff counts:
116
+ `src/generated/**`, `python/serenity_project_engine/**`.
117
+
118
+ `datamodel-code-generator` emits a **package** (`model.py`, `aiseo.py`, `http_server.py`,
119
+ `__init__.py`) rather than a single `models.py`: the vendored spec's Go-style dotted schema
120
+ names (`model.X`, `aiseo.X`, `http_server.X`) are modular references, which the generator maps
121
+ to one module per prefix. This is a tool-driven layout choice, not a spec edit.
122
+ - **Gitignored intermediate:** `build/openapi3.json`, `.counterfact/`.
123
+
124
+ ## Notes
125
+
126
+ - The package is `@adobe/spacecat-shared-*` and lives under the monorepo `packages/` layout.
127
+ - Pydantic v2 is the default target; switch the `--output-model-type` flag in
128
+ `generate:pydantic` if a consumer needs v1.
129
+ - Known spec-hygiene quirks the tooling surfaces (vendored as-is, not patched): a duplicated
130
+ parameter block on `GET .../issue_rules`, `id`-in-query-vs-path inconsistencies on some AIO
131
+ category/tag endpoints, and deprecated `keywords`/`tags` endpoints plus a deprecated v1
132
+ benchmarks `POST`.
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@adobe/spacecat-shared-project-engine-client",
3
+ "version": "1.1.0",
4
+ "description": "Shared modules of the Spacecat Services - Semrush Project Engine client and generated types",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "types": "src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "src"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22.0.0 <25.0.0",
19
+ "npm": ">=10.9.0 <12.0.0"
20
+ },
21
+ "scripts": {
22
+ "test": "c8 mocha",
23
+ "lint": "eslint .",
24
+ "lint:fix": "eslint --fix .",
25
+ "clean": "rm -rf node_modules build .counterfact",
26
+ "spec:convert": "mkdir -p build && swagger2openapi spec/projectengine_swagger_public.yaml --patch --outfile build/openapi3.json",
27
+ "spec:overlay": "node scripts/apply-overlay.mjs",
28
+ "generate:ts": "openapi-typescript build/openapi3.json --output src/generated/types.ts",
29
+ "generate:pydantic": "datamodel-codegen --input build/openapi3.json --input-file-type openapi --output python/serenity_project_engine/ --output-model-type pydantic_v2.BaseModel",
30
+ "generate": "npm run spec:convert && npm run spec:overlay && npm run generate:ts && npm run generate:pydantic",
31
+ "mock": "counterfact spec/projectengine_swagger_public.yaml .counterfact --port 4010"
32
+ },
33
+ "mocha": {
34
+ "reporter": "mocha-multi-reporters",
35
+ "reporter-options": "configFile=.mocha-multi.json",
36
+ "spec": "test/**/*.test.js"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/adobe/spacecat-shared.git"
41
+ },
42
+ "author": "",
43
+ "license": "Apache-2.0",
44
+ "bugs": {
45
+ "url": "https://github.com/adobe/spacecat-shared/issues"
46
+ },
47
+ "homepage": "https://github.com/adobe/spacecat-shared/packages/spacecat-shared-project-engine-client/#readme",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "dependencies": {
52
+ "openapi-fetch": "0.17.0"
53
+ },
54
+ "devDependencies": {
55
+ "c8": "11.0.0",
56
+ "chai": "6.2.2",
57
+ "counterfact": "2.14.0",
58
+ "js-yaml": "4.2.0",
59
+ "mocha": "11.7.6",
60
+ "mocha-multi-reporters": "1.5.1",
61
+ "openapi-typescript": "7.13.0",
62
+ "sinon": "22.0.0",
63
+ "swagger2openapi": "7.0.8"
64
+ }
65
+ }
package/src/client.js ADDED
@@ -0,0 +1,133 @@
1
+ /*
2
+ * Copyright 2026 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import createClient from 'openapi-fetch';
14
+ import { createRetryingFetch, toTokenGetter } from './internal.js';
15
+
16
+ /**
17
+ * @typedef {import('./internal.js').AuthTokenSource} AuthTokenSource
18
+ */
19
+
20
+ /**
21
+ * A fully-typed Project Engine client (all operations from the generated `paths`).
22
+ * @typedef {import('openapi-fetch').Client<import('./generated/types.js').paths>}
23
+ * SerenityProjectEngineApiClient
24
+ */
25
+
26
+ /**
27
+ * @typedef {object} SerenityProjectEngineApiClientOptions
28
+ * @property {string} baseUrl Base URL of the Project Engine API — the origin of
29
+ * `SEMRUSH_PROJECTS_BASE_URL` (e.g. `https://adobe-hackathon.semrush.com`), or the Counterfact
30
+ * mock's origin for E2E / local dev. Only `protocol//host` is used; any path is dropped and the
31
+ * client appends the fixed `/enterprise/projects/api` prefix itself, matching the deployed
32
+ * api-service transport (`rest-transport.js`).
33
+ * @property {AuthTokenSource} authToken The caller's IMS JWT, or a (sync/async) getter resolved
34
+ * per request. Sent as the `Authorization: Bearer <token>` header. The client performs NO token
35
+ * exchange or minting — Semrush accepts the IMS bearer token directly, so the caller's token is
36
+ * forwarded as-is.
37
+ * @property {number} [maxRetries=2] Retry attempts on 429 / retryable 5xx / network error.
38
+ * Default 2 (3 tries total).
39
+ * @property {number} [retryBaseDelayMs=200] Base backoff in ms; grows exponentially per
40
+ * attempt. Default 200.
41
+ * @property {import('./internal.js').OnRetry} [onRetry] Best-effort hook invoked before each
42
+ * retry sleep (`{ attempt, delayMs, method, status?, error? }`), for logging/metrics. A retry
43
+ * loop is otherwise silent — an operator can't tell "slow upstream" from "stuck in backoff". A
44
+ * throwing or rejecting hook is swallowed and never affects the request.
45
+ * @property {typeof globalThis.fetch} [fetch] Injectable fetch (tests, custom agents).
46
+ * Defaults to the global fetch.
47
+ */
48
+
49
+ /**
50
+ * The Project Engine API path prefix — the vendored spec's `basePath`. The generated `paths`
51
+ * keys are relative to it, so the client owns it here, mirroring the deployed api-service
52
+ * transport (`rest-transport.js`), which appends this same constant to the env-configured origin.
53
+ */
54
+ const API_PREFIX = '/enterprise/projects/api';
55
+
56
+ /**
57
+ * Normalises the caller's base URL to `<origin>/enterprise/projects/api`, mirroring
58
+ * `rest-transport.js`: parse, keep only `protocol//host` — dropping any path or credentials so a
59
+ * misconfigured value can't bleed into every request — then append the fixed prefix. Unlike the
60
+ * prod-only transport it does NOT force https, since the client also targets the local Counterfact
61
+ * mock over http.
62
+ * @param {string} baseUrl
63
+ * @returns {string}
64
+ */
65
+ function resolveBaseUrl(baseUrl) {
66
+ let parsed;
67
+ try {
68
+ parsed = new URL(baseUrl);
69
+ } catch {
70
+ throw new Error(`Project Engine client: invalid baseUrl ${JSON.stringify(baseUrl)}`);
71
+ }
72
+ // Restrict to http(s) so a `file:`/`ftp:`/etc. URL fails fast here with an actionable message
73
+ // rather than deep inside fetch(). Both schemes are allowed — https for prod, http for the
74
+ // local Counterfact mock.
75
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
76
+ throw new Error(
77
+ `Project Engine client: baseUrl must be http(s), got ${parsed.protocol} in ${JSON.stringify(baseUrl)}`,
78
+ );
79
+ }
80
+ return `${parsed.protocol}//${parsed.host}${API_PREFIX}`;
81
+ }
82
+
83
+ /**
84
+ * Builds the openapi-fetch middleware that authenticates each request with the caller's IMS token
85
+ * as `Authorization: Bearer <token>` — the auth model proven by the deployed api-service transport
86
+ * (`rest-transport.js`). Semrush accepts the IMS bearer directly; the client mints/exchanges
87
+ * nothing.
88
+ * @param {() => string | Promise<string>} getToken
89
+ * @returns {import('openapi-fetch').Middleware}
90
+ */
91
+ function authMiddleware(getToken) {
92
+ return {
93
+ async onRequest({ request }) {
94
+ const token = await getToken();
95
+ // Fail fast on a missing token rather than sending `Bearer undefined` (or an empty header),
96
+ // which Semrush would reject with an opaque 401.
97
+ if (!token) {
98
+ throw new Error('Project Engine client: authToken resolved to an empty value');
99
+ }
100
+ request.headers.set('Authorization', `Bearer ${token}`);
101
+ return request;
102
+ },
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Creates a thin, typed client over the generated Project Engine `paths`. It owns the base
108
+ * URL (origin + `/enterprise/projects/api`), retries, and authenticating each request with the
109
+ * caller's IMS JWT as `Authorization: Bearer` — and nothing else; request/response shapes come
110
+ * straight from the generated types.
111
+ * @param {SerenityProjectEngineApiClientOptions} options
112
+ * @returns {SerenityProjectEngineApiClient}
113
+ */
114
+ export function createSerenityProjectEngineApiClient(options) {
115
+ const {
116
+ baseUrl,
117
+ authToken,
118
+ maxRetries = 2,
119
+ retryBaseDelayMs = 200,
120
+ onRetry,
121
+ fetch: injectedFetch = globalThis.fetch,
122
+ } = options;
123
+
124
+ const client = createClient({
125
+ baseUrl: resolveBaseUrl(baseUrl),
126
+ fetch: createRetryingFetch(injectedFetch, maxRetries, retryBaseDelayMs, onRetry),
127
+ });
128
+ // Auth runs as openapi-fetch middleware, so the token getter resolves once per logical request
129
+ // and that token is reused across the request's retries (the retry layer clones the same Request
130
+ // — see createRetryingFetch). toTokenGetter() rejects a non-string/function authToken up front.
131
+ client.use(authMiddleware(toTokenGetter(authToken)));
132
+ return client;
133
+ }