@grafctory/keep-rest 0.0.0-stage → 0.15.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 ADDED
@@ -0,0 +1,201 @@
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 of
133
+ 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 the
141
+ 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.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # @grafctory/keep-rest
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
+ [![npm](https://img.shields.io/npm/v/@grafctory/keep-rest)](https://www.npmjs.com/package/@grafctory/keep-rest)
4
+
5
+ REST/JSON proxy connector for the [@grafctory/keep](https://github.com/grafctory/keep) model-driven linked data storage
6
+ framework.
7
+
8
+ Gives an application access to a remote REST service through the same
9
+ [`Store`](https://grafctory.github.io/keep/modules/_grafctory_keep.html) API as every other connector: each data operation
10
+ is round-tripped to the service rather than applied to a local backing store. Inputs are shape-validated before the
11
+ request is sent. Retrieval responses are validated as well, since the remote service is treated as untrusted by default.
12
+
13
+ > [!IMPORTANT]
14
+ > **Transaction Isolation** — None. REST has no native transaction support: operations apply eagerly with no
15
+ > cross-call isolation, and an `execute` task that throws after partial server-side mutations does not roll them back.
16
+
17
+ > [!IMPORTANT]
18
+ > **Mutation Events** — Limited to mutations issued through this store; mutations from other clients sharing the remote
19
+ > service are not observed.
20
+
21
+ # Installation
22
+
23
+ ```shell
24
+ npm install @grafctory/keep-rest
25
+ ```
26
+
27
+ # Usage
28
+
29
+ > [!NOTE]
30
+ >
31
+ > This section introduces essential concepts; for complete coverage, see the
32
+ > [API reference](https://grafctory.github.io/keep/modules/_grafctory_keep-rest.html).
33
+
34
+ ## Wiring a Store
35
+
36
+ Call `createRESTStore` to obtain a `Store` proxying a remote REST service over the global `fetch`:
37
+
38
+ ```typescript
39
+ import { createRESTStore } from "@grafctory/keep-rest";
40
+
41
+ const store = createRESTStore();
42
+
43
+ const product = await store.lookup({
44
+ entry: "http://example.com/products/1",
45
+ shape: ProductShape,
46
+ model: {
47
+ name: {},
48
+ price: {}
49
+ }
50
+ });
51
+ ```
52
+
53
+ Pass a `fetch`-compatible transport as the `fetch` option to route requests through a configured client, for instance
54
+ one adding authentication headers. Pass `trusted: true` to skip validation of retrieval responses, but only when the
55
+ remote service is trusted to deliver shape-conforming data.
56
+
57
+ # Support
58
+
59
+ - open an [issue](https://github.com/grafctory/keep/issues) to report a problem or to suggest a new feature
60
+ - start a [discussion](https://github.com/grafctory/keep/discussions) to ask a how-to question or to share an idea
61
+
62
+ # License
63
+
64
+ This project is licensed under the Apache 2.0 License –
65
+ see [LICENSE](https://github.com/grafctory/keep?tab=Apache-2.0-1-ov-file) file for details.
@@ -0,0 +1,42 @@
1
+ import type { Store } from "@grafctory/keep";
2
+ /**
3
+ * Creates a REST proxy store backed by a remote REST service.
4
+ *
5
+ * Exposes a remote REST service through the standard {@link Store} API, so an application drives it with the same
6
+ * calls as any local backend. Each data operation round-trips to the service over the configured `fetch` transport.
7
+ * The module description details the request and response contract, the validation rules and the miss-code handling.
8
+ *
9
+ * > [!IMPORTANT]
10
+ * > **Transaction Isolation** — None. REST has no native transaction support: operations apply eagerly with no
11
+ * > cross-call isolation, and a {@link Store.execute execute} task that throws after partial server-side mutations
12
+ * > does not roll them back.
13
+ *
14
+ * > [!IMPORTANT]
15
+ * > **Mutation Events** — Limited to mutations issued through this store; mutations from other clients sharing the
16
+ * > remote service are not observed.
17
+ *
18
+ * @param options - Optional proxy options
19
+ *
20
+ * @returns An immutable {@link Store} proxying the remote REST service
21
+ */
22
+ export declare function createRESTStore({ trusted, fetch }?: {
23
+ /**
24
+ * Whether to accept {@link Store.lookup lookup} responses without validating them against the shape narrowed by
25
+ * the caller's `model`.
26
+ *
27
+ * Enabling it suits only a service trusted to deliver shape-conforming data, as responses then reach the caller
28
+ * unchecked.
29
+ *
30
+ * @defaultValue `false`, treating the remote endpoint as untrusted
31
+ */
32
+ readonly trusted?: boolean;
33
+ /**
34
+ * {@link !fetch fetch}-compatible transport used for every HTTP request.
35
+ *
36
+ * A configured client adds authentication, custom headers, or other cross-cutting request handling.
37
+ *
38
+ * @defaultValue The global {@link !fetch fetch}
39
+ */
40
+ readonly fetch?: typeof globalThis.fetch;
41
+ }): Store;
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAuGA,OAAO,KAAK,EAAE,KAAK,EAAc,MAAM,iBAAiB,CAAC;AAOzD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,EAE/B,OAAe,EAEf,KAAwB,EAExB,GAAE;IAEF;;;;;;;;OAQG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAE1B;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;CAEnC,GAAG,KAAK,CAsQb"}
package/dist/index.js ADDED
@@ -0,0 +1,290 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * REST/JSON proxy connector.
18
+ *
19
+ * Gives an application access to a remote REST service through the standard {@link Store} API.
20
+ * {@link createRESTStore} returns a store with the same surface as every other connector. Each data operation is
21
+ * round-tripped to the service rather than applied to a local backing store.
22
+ *
23
+ * | Operation | HTTP | `Prefer` | Behaviour | Validated |
24
+ * |---|---|---|---|---|
25
+ * | {@link Store.lookup lookup} | `GET` | — | Template in query string; `404` → `undefined`; `virtual` rejected | `model`, response |
26
+ * | {@link Store.create create} | `POST` | — | Child IRI from `Location`; `409` → `undefined` | `model`, `state` |
27
+ * | {@link Store.update update} | `PUT` | — | Conditional; `404` → `undefined` | `state` |
28
+ * | {@link Store.delete delete} | `DELETE` | — | Conditional; `404` → `undefined` | — |
29
+ * | {@link Store.insert insert} | `PUT` | `handling=lenient` | Unconditional upsert | `state` |
30
+ * | {@link Store.remove remove} | `DELETE` | `handling=lenient` | Unconditional; `404` silently ignored | — |
31
+ *
32
+ * > [!IMPORTANT]
33
+ * > Each mutating HTTP verb is shared by a conditional and an unconditional method, disambiguated through the
34
+ * > RFC 7240 `Prefer` request header:
35
+ * >
36
+ * > - **Conditional** ({@link Store.update update} via `PUT`, {@link Store.delete delete} via `DELETE`) send bare
37
+ * > requests, so the server rejects a missing target with `404`.
38
+ * > - **Unconditional** ({@link Store.insert insert} via `PUT`, {@link Store.remove remove} via `DELETE`) send
39
+ * > `Prefer: handling=lenient`, so a `PUT` against a missing resource becomes an upsert and a `DELETE` against one
40
+ * > succeeds silently.
41
+ * >
42
+ * > Servers that ignore the header degrade to the conditional behaviour: {@link Store.insert insert} against a
43
+ * > missing resource then rejects with a `404` {@link @grafctory/http!Problem | Problem}.
44
+ *
45
+ * Beyond the per-operation miss codes tabulated above, every remote failure surfaces as a
46
+ * {@link @grafctory/http!Problem | Problem} rejection. This covers non-OK responses as well as protocol anomalies on
47
+ * otherwise successful responses, such as a missing `Location` header or a malformed response body. Callers therefore
48
+ * handle every remote failure through a single rejection type.
49
+ *
50
+ * {@link Store.create create} posts only the `state` of the new resource. The `model` slice naming the collecting
51
+ * property is validated locally but not sent, so the service identifies the collection from `entry` alone.
52
+ *
53
+ * {@link Store.create create} resolves the returned `Location` against the request `entry` per RFC 3986 § 5.2.
54
+ * Standard merge semantics apply, so an `entry` without a trailing `/` strips its last path segment before merging.
55
+ * The resolved IRI must lie strictly below the container `entry` resolves to, that is `entry` itself when it ends
56
+ * with `/` and its parent otherwise: a `Location` outside that scope, whether on a foreign origin or elsewhere on the
57
+ * same one, rejects with a {@link @grafctory/http!Problem | Problem}, so a misbehaving service can't make the caller
58
+ * adopt a foreign child IRI. An unparseable `Location` surfaces as a {@link !RangeError RangeError} rather than a
59
+ * {@link @grafctory/http!Problem | Problem}.
60
+ *
61
+ * {@link Store.lookup lookup} carries its `model` as a base64url query string, so any template (filter operators
62
+ * such as `~name` and `>=price`, nested shapes, aggregates, collection pagination) survives transport intact. An
63
+ * empty template omits the query string. The scope `locale` is forwarded as an `Accept-Language` header, with a
64
+ * trailing `*` fallback so the service may answer in any language when none of the listed ones is available. A
65
+ * `virtual` lookup is rejected with a {@link !RangeError RangeError} before any request is sent: the REST contract
66
+ * carries no such flag, and the service alone decides which resources it derives rather than holds.
67
+ *
68
+ * IRIs on the origin of `entry` travel in root-relative form (`/…`), both in request templates and states and in
69
+ * {@link Store.lookup lookup} responses. Root-relative references in a response are resolved against the origin of
70
+ * `entry`, so the service may return them in place of absolute IRIs. Any other relative reference is rejected by
71
+ * response validation.
72
+ *
73
+ * > [!IMPORTANT]
74
+ * > `entry` parameters MUST be bare absolute IRIs with no query string (`?…`) or fragment (`#…`). A query string
75
+ * > would collide with the template carried by {@link Store.lookup lookup}, and a fragment would be stripped by
76
+ * > {@link !fetch fetch} before the request reached the wire. Non-conforming entries are rejected with a
77
+ * > {@link !RangeError RangeError} on every method.
78
+ *
79
+ * Inputs are validated against the shape before the network call: `model` on {@link Store.lookup lookup} and
80
+ * {@link Store.create create}, `state` on every mutation carrying one. The query-complexity bounds of the
81
+ * {@link StoreScope | retrieval scope} are also enforced locally, so a rejected template never reaches the service.
82
+ * Because the remote endpoint is untrusted by default, {@link Store.lookup lookup} responses are also validated
83
+ * against the shape narrowed by the caller's `model`. Failures reject with a
84
+ * {@link @grafctory/core!TraceError | TraceError} carrying `"invalid model"`, `"invalid state"`, or
85
+ * `"invalid response"`, per the unified {@link Store} error channel.
86
+ *
87
+ * @see {@link https://www.rfc-editor.org/rfc/rfc3986 RFC 3986 — URI Generic Syntax}
88
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7240 RFC 7240 — Prefer Header for HTTP}
89
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9110 RFC 9110 — HTTP Semantics}
90
+ *
91
+ * @group Connectors
92
+ *
93
+ * @module index
94
+ */
95
+ import { isError, isObject } from "@grafctory/core";
96
+ import { getIRIBase, resolve } from "@grafctory/core/resource";
97
+ import { immutable } from "@grafctory/core/values";
98
+ import { Conflict, createFetch, NotFound } from "@grafctory/http";
99
+ import { success } from "@grafctory/http/success";
100
+ import { transport } from "@grafctory/http/transport";
101
+ import { createManagingStore } from "@grafctory/keep/managing";
102
+ import { createValidatingStore } from "@grafctory/keep/validating";
103
+ import { encodeTemplate } from "@grafctory/qest/model";
104
+ import { decodeResource, encodeResource } from "@grafctory/qest/state";
105
+ /**
106
+ * Creates a REST proxy store backed by a remote REST service.
107
+ *
108
+ * Exposes a remote REST service through the standard {@link Store} API, so an application drives it with the same
109
+ * calls as any local backend. Each data operation round-trips to the service over the configured `fetch` transport.
110
+ * The module description details the request and response contract, the validation rules and the miss-code handling.
111
+ *
112
+ * > [!IMPORTANT]
113
+ * > **Transaction Isolation** — None. REST has no native transaction support: operations apply eagerly with no
114
+ * > cross-call isolation, and a {@link Store.execute execute} task that throws after partial server-side mutations
115
+ * > does not roll them back.
116
+ *
117
+ * > [!IMPORTANT]
118
+ * > **Mutation Events** — Limited to mutations issued through this store; mutations from other clients sharing the
119
+ * > remote service are not observed.
120
+ *
121
+ * @param options - Optional proxy options
122
+ *
123
+ * @returns An immutable {@link Store} proxying the remote REST service
124
+ */
125
+ export function createRESTStore({ trusted = false, fetch = globalThis.fetch } = {}) {
126
+ const remote = createFetch(success(), transport(fetch));
127
+ function retrieve(entry, model, opts) {
128
+ const url = Object.keys(model).length === 0 ? entry
129
+ : `${entry}?${encodeTemplate(model, { base: getIRIBase(entry), format: "base64" })}`;
130
+ return remote(url, {
131
+ method: "GET",
132
+ headers: {
133
+ "Accept": "application/json",
134
+ ...(opts?.locale?.length ? { "Accept-Language": acceptLanguage(opts.locale) } : {})
135
+ }
136
+ }).then(response => {
137
+ // ;(cast) the decoded body is only resolved, not checked: the wrapping validating store validates it
138
+ // against the requested shape and model, unless the endpoint is trusted to deliver conforming data
139
+ return response.text().then(json => decodeResource(json, {
140
+ lenient: true,
141
+ base: getIRIBase(entry)
142
+ })).catch(e => {
143
+ throw immutable({
144
+ detail: `malformed JSON in response to GET <${entry}>: ${isError(e) ? e.message : String(e)}`
145
+ });
146
+ });
147
+ }).catch(e => {
148
+ return isProblem(e, NotFound) ? undefined : Promise.reject(e);
149
+ });
150
+ }
151
+ const client = createValidatingStore(immutable({
152
+ lookup({ virtual, entry, model }, opts) {
153
+ // the REST contract carries no virtual flag and the service alone decides what it derives, so the
154
+ // request is refused before any call rather than silently served as held, which the caller couldn't tell
155
+ return virtual === true
156
+ ? Promise.reject(new RangeError(`unsupported virtual lookup of <${entry}>`))
157
+ : retrieve(entry, model, opts);
158
+ },
159
+ create({ entry, state }) {
160
+ return remote(entry, {
161
+ method: "POST",
162
+ headers: {
163
+ "Content-Type": "application/json"
164
+ },
165
+ body: encodeResource(state, { base: getIRIBase(entry) })
166
+ }).then(response => {
167
+ const location = response.headers.get("Location");
168
+ if (location === null) {
169
+ throw immutable({ detail: `missing <Location> header in response to POST <${entry}>` });
170
+ }
171
+ const iri = resolve(entry, location);
172
+ const container = resolve(entry, ".");
173
+ if (iri === container || !iri.startsWith(container)) {
174
+ throw immutable({
175
+ detail: `out-of-scope <Location> header <${iri}> in response to POST <${entry}>`
176
+ });
177
+ }
178
+ return iri;
179
+ }).catch(e => {
180
+ return isProblem(e, Conflict) ? undefined : Promise.reject(e);
181
+ });
182
+ },
183
+ update({ entry, state }) {
184
+ return remote(entry, {
185
+ method: "PUT",
186
+ headers: {
187
+ "Content-Type": "application/json"
188
+ },
189
+ body: encodeResource(state, { base: getIRIBase(entry) })
190
+ }).then(() => {
191
+ return entry;
192
+ }).catch(e => {
193
+ return isProblem(e, NotFound) ? undefined : Promise.reject(e);
194
+ });
195
+ },
196
+ delete({ entry }) {
197
+ return remote(entry, {
198
+ method: "DELETE"
199
+ }).then(() => {
200
+ return entry;
201
+ }).catch(e => {
202
+ return isProblem(e, NotFound) ? undefined : Promise.reject(e);
203
+ });
204
+ },
205
+ insert({ entry, state }) {
206
+ return remote(entry, {
207
+ method: "PUT",
208
+ headers: {
209
+ "Content-Type": "application/json",
210
+ "Prefer": "handling=lenient"
211
+ },
212
+ body: encodeResource(state, { base: getIRIBase(entry) })
213
+ }).then(() => {
214
+ return entry;
215
+ }).catch(e => {
216
+ return Promise.reject(e); // unconditional insert — all errors propagate as-is
217
+ });
218
+ },
219
+ remove({ entry }) {
220
+ return remote(entry, {
221
+ method: "DELETE",
222
+ headers: {
223
+ "Prefer": "handling=lenient"
224
+ }
225
+ }).then(() => {
226
+ return entry;
227
+ }).catch(e => {
228
+ return isProblem(e, NotFound) ? entry : Promise.reject(e); // unconditional remove — 404 is a silent
229
+ // no-op
230
+ });
231
+ }
232
+ }), {
233
+ trusted
234
+ });
235
+ // REST has no transaction primitive: each call of a task goes straight to the service
236
+ return createManagingStore({
237
+ execute: task => Promise.resolve().then(() => task(client))
238
+ });
239
+ /**
240
+ * Tests whether a caught value is a {@link @grafctory/http!Problem | Problem} carrying the given HTTP status.
241
+ *
242
+ * Tells expected miss codes (`404`, `409`) apart from every other {@link @grafctory/http!Problem | Problem}.
243
+ * {@link @grafctory/http!Problem | Problem} is an interface rather than a class, so any object with a matching
244
+ * numeric `status` property is accepted. This is sound because {@link @grafctory/http!createFetch | createFetch} is
245
+ * the only source of status-carrying errors in scope, and it always throws
246
+ * {@link @grafctory/http!Problem | Problem}-shaped values.
247
+ *
248
+ * @param error - Value caught from a proxy `.catch` branch
249
+ * @param status - HTTP status code to match against
250
+ *
251
+ * @returns true if `error` is an object whose `status` matches the expected code; false otherwise
252
+ */
253
+ function isProblem(error, status) {
254
+ return isObject(error) && error.status === status;
255
+ }
256
+ /**
257
+ * Builds an RFC 9110 `Accept-Language` header value from a locale priority list.
258
+ *
259
+ * Assigns each tag a descending quality factor by its position and appends a `*` wildcard fallback at the lowest
260
+ * factor so the server always has an acceptable last resort. With `total` set to `locale.length + 1` (reserving
261
+ * the lowest rung for the wildcard), the tag at position `k` weighs `(total - k) / total` and `*` weighs
262
+ * `1 / total`, each rounded to three decimal places. Every range carries an explicit `q`, including the
263
+ * most-preferred tag (`q=1`).
264
+ *
265
+ * @param locale - Non-empty language-negotiation priority list, most-preferred first
266
+ *
267
+ * @returns A comma-separated `Accept-Language` value carrying descending `q` weights and a trailing `*` fallback
268
+ *
269
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9110#name-accept-language RFC 9110 § 12.5.4 Accept-Language}
270
+ */
271
+ function acceptLanguage(locale) {
272
+ const total = locale.length + 1; // +1 reserves the lowest rung for the `*` wildcard fallback
273
+ return [
274
+ ...locale.map((tag, index) => weighted(tag, (total - index) / total)),
275
+ weighted("*", 1 / total)
276
+ ].join(", ");
277
+ }
278
+ /**
279
+ * Formats a language range with an explicit quality factor.
280
+ *
281
+ * @param range - Language tag or the `*` wildcard
282
+ * @param quality - Quality factor in `(0, 1]`, rendered with up to three decimal places
283
+ *
284
+ * @returns The `range;q=<quality>` token
285
+ */
286
+ function weighted(range, quality) {
287
+ return `${range};q=${Number(quality.toFixed(3))}`;
288
+ }
289
+ }
290
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8EG;AAEH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAiB,MA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,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,KAAK,GAAC,KAAK,CAAC,GAAC,KAAK,CAAC,CAAC;YACjE,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAC,KAAK,CAAC;SACtB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,CAAC;IAED;;;;;;;OAOG;IACH,SAAS,QAAQ,CAAC,KAAa,EAAE,OAAe;QAC/C,OAAO,GAAG,KAAK,MAAM,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACnD,CAAC;AAEF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@grafctory/keep-rest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.15.0",
4
+ "description": "REST/JSON proxy connector for @grafctory/keep.",
5
+ "keywords": [
6
+ "typescript",
7
+ "json-ld",
8
+ "model-driven",
9
+ "rest"
10
+ ],
11
+ "homepage": "https://grafctory.github.io/keep/",
12
+ "bugs": {
13
+ "url": "https://github.com/grafctory/keep/issues",
14
+ "email": "info@grafctory.dev"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "author": {
18
+ "name": "Metreeca",
19
+ "email": "info@metreeca.com",
20
+ "url": "https://www.metreeca.com/"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/grafctory/keep.git",
25
+ "directory": "packages/connectors/keep-rest"
26
+ },
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "@grafctory/source": "./src/index.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "README.md",
37
+ "LICENSE",
38
+ "dist"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.22.0"
42
+ },
43
+ "scripts": {
44
+ "clean": "ush rm dist docs node_modules",
45
+ "build": "ush rm dist && tsc -p tsconfig.build.json",
46
+ "check": "npx vitest --typecheck run"
47
+ },
48
+ "dependencies": {
49
+ "@grafctory/core": "^0.14.0",
50
+ "@grafctory/http": "^0.6.0",
51
+ "@grafctory/keep": "^0.15.0",
52
+ "@grafctory/qest": "^0.15.0"
53
+ },
54
+ "devDependencies": {
55
+ "@grafctory/blue": "^0.16.0",
56
+ "typescript": "^6.0.3",
57
+ "vitest": "^4.0.13"
58
+ }
59
+ }