@bjornharrtell/json-api 5.2.0 → 5.2.2
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/dist/docs/assets/search.js +1 -1
- package/dist/docs/enums/RelationshipType.html +2 -2
- package/dist/docs/functions/camel.html +1 -1
- package/dist/docs/functions/useJsonApi.html +1 -1
- package/dist/docs/interfaces/AtomicOperation.html +3 -2
- package/dist/docs/interfaces/BaseEntity.html +2 -2
- package/dist/docs/interfaces/FetchOptions.html +2 -2
- package/dist/docs/interfaces/FetchParams.html +1 -1
- package/dist/docs/interfaces/JsonApiAtomicDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiAtomicOperation.html +2 -2
- package/dist/docs/interfaces/JsonApiAtomicResult.html +2 -2
- package/dist/docs/interfaces/JsonApiConfig.html +4 -4
- package/dist/docs/interfaces/JsonApiDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiError.html +2 -2
- package/dist/docs/interfaces/JsonApiLinkObject.html +2 -2
- package/dist/docs/interfaces/JsonApiLinks.html +2 -2
- package/dist/docs/interfaces/JsonApiMeta.html +2 -2
- package/dist/docs/interfaces/JsonApiRelationship.html +2 -2
- package/dist/docs/interfaces/JsonApiResource.html +2 -2
- package/dist/docs/interfaces/JsonApiResourceIdentifier.html +2 -2
- package/dist/docs/interfaces/ModelDefinition.html +3 -3
- package/dist/docs/interfaces/PageOption.html +2 -2
- package/dist/docs/interfaces/Relationship.html +3 -3
- package/dist/docs/types/JsonApi.html +1 -1
- package/dist/docs/types/JsonApiFetcher.html +1 -1
- package/dist/docs/types/JsonApiLink.html +1 -1
- package/dist/lib.d.ts +2 -1
- package/dist/lib.js +176 -175
- package/dist/lib.js.map +1 -1
- package/package.json +1 -1
package/dist/lib.js
CHANGED
|
@@ -1,240 +1,241 @@
|
|
|
1
|
-
function
|
|
2
|
-
return new URL(
|
|
1
|
+
function O(...o) {
|
|
2
|
+
return new URL(o.join("/")).href;
|
|
3
3
|
}
|
|
4
|
-
class
|
|
5
|
-
constructor(t,
|
|
6
|
-
super(t), this.status =
|
|
4
|
+
class P extends Error {
|
|
5
|
+
constructor(t, n, d) {
|
|
6
|
+
super(t), this.status = n, this.body = d, this.name = "HttpError";
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
async function U(
|
|
10
|
-
if (n.ok) return;
|
|
11
|
-
let t = `HTTP error! status: ${n.status} ${n.statusText}`, e;
|
|
9
|
+
async function U(o) {
|
|
12
10
|
try {
|
|
13
|
-
|
|
14
|
-
const r = e.errors[0];
|
|
15
|
-
t += ` - ${r.title}: ${r.detail ?? ""}`;
|
|
16
|
-
}
|
|
11
|
+
return await o.json();
|
|
17
12
|
} catch {
|
|
18
13
|
}
|
|
19
|
-
throw new B(t, n.status, e);
|
|
20
14
|
}
|
|
21
|
-
async function
|
|
22
|
-
const { headers:
|
|
23
|
-
method:
|
|
24
|
-
headers:
|
|
25
|
-
signal:
|
|
26
|
-
body:
|
|
27
|
-
});
|
|
28
|
-
|
|
15
|
+
async function T(o, t) {
|
|
16
|
+
const { headers: n, searchParams: d, method: r, signal: u, body: p } = t, y = d ? `?${d}` : "", g = o.replace(/(?:\?.*?)?(?=#|$)/, y), b = await fetch(g, {
|
|
17
|
+
method: r,
|
|
18
|
+
headers: n,
|
|
19
|
+
signal: u,
|
|
20
|
+
body: p
|
|
21
|
+
}), v = await U(b);
|
|
22
|
+
if (!b.ok)
|
|
23
|
+
throw new P(`HTTP error! status: ${b.status} ${b.statusText}`, b.status, v);
|
|
24
|
+
return v;
|
|
29
25
|
}
|
|
30
|
-
async function C(
|
|
31
|
-
const { signal:
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
method:
|
|
35
|
-
headers:
|
|
36
|
-
signal:
|
|
37
|
-
body:
|
|
38
|
-
});
|
|
39
|
-
|
|
26
|
+
async function C(o, t) {
|
|
27
|
+
const { signal: n, body: d } = t, r = "POST", u = new Headers(t.headers ?? {});
|
|
28
|
+
u.append("Accept", 'application/vnd.api+json; ext="https://jsonapi.org/ext/atomic"'), u.append("Content-Type", 'application/vnd.api+json; ext="https://jsonapi.org/ext/atomic"');
|
|
29
|
+
const p = await fetch(o, {
|
|
30
|
+
method: r,
|
|
31
|
+
headers: u,
|
|
32
|
+
signal: n,
|
|
33
|
+
body: d
|
|
34
|
+
}), y = await U(p);
|
|
35
|
+
if (!p.ok)
|
|
36
|
+
throw new P(`HTTP error! status: ${p.status} ${p.statusText}`, p.status, y);
|
|
37
|
+
return p.status === 204 ? void 0 : y;
|
|
40
38
|
}
|
|
41
|
-
class
|
|
39
|
+
class J {
|
|
42
40
|
constructor(t) {
|
|
43
41
|
this.endpoint = t;
|
|
44
42
|
}
|
|
45
|
-
createOptions(t = {},
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
const
|
|
43
|
+
createOptions(t = {}, n = {}, d) {
|
|
44
|
+
const r = new URLSearchParams(), u = new Headers(t.headers ?? {});
|
|
45
|
+
u.append("Accept", "application/vnd.api+json");
|
|
46
|
+
const p = { searchParams: r, headers: u, body: d };
|
|
49
47
|
if (t.fields)
|
|
50
|
-
for (const [
|
|
51
|
-
t.page?.size &&
|
|
52
|
-
for (const [
|
|
53
|
-
return
|
|
54
|
-
}
|
|
55
|
-
async fetchDocument(t,
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
return await
|
|
60
|
-
}
|
|
61
|
-
async fetchAll(t,
|
|
62
|
-
const
|
|
63
|
-
return (await
|
|
64
|
-
}
|
|
65
|
-
async fetchOne(t,
|
|
66
|
-
const
|
|
67
|
-
return (await
|
|
68
|
-
}
|
|
69
|
-
async fetchHasMany(t,
|
|
70
|
-
const
|
|
71
|
-
return await
|
|
72
|
-
}
|
|
73
|
-
async fetchBelongsTo(t,
|
|
74
|
-
const
|
|
75
|
-
return await
|
|
76
|
-
}
|
|
77
|
-
async post(t,
|
|
78
|
-
const
|
|
48
|
+
for (const [y, g] of Object.entries(t.fields)) r.append(`fields[${y}]`, g.join(","));
|
|
49
|
+
t.page?.size && r.append("page[size]", t.page.size.toString()), t.page?.number && r.append("page[number]", t.page.number.toString()), t.include && r.append("include", t.include.join(",")), t.filter && r.append("filter", t.filter);
|
|
50
|
+
for (const [y, g] of Object.entries(n)) r.append(y, g);
|
|
51
|
+
return p;
|
|
52
|
+
}
|
|
53
|
+
async fetchDocument(t, n, d, r) {
|
|
54
|
+
const u = [this.endpoint, t];
|
|
55
|
+
n && u.push(n);
|
|
56
|
+
const p = O(...u);
|
|
57
|
+
return await T(p, this.createOptions(d, r));
|
|
58
|
+
}
|
|
59
|
+
async fetchAll(t, n, d) {
|
|
60
|
+
const r = O(this.endpoint, t);
|
|
61
|
+
return (await T(r, this.createOptions(n, d))).data;
|
|
62
|
+
}
|
|
63
|
+
async fetchOne(t, n, d, r) {
|
|
64
|
+
const u = O(this.endpoint, t, n);
|
|
65
|
+
return (await T(u, this.createOptions(d, r))).data;
|
|
66
|
+
}
|
|
67
|
+
async fetchHasMany(t, n, d, r, u) {
|
|
68
|
+
const p = O(this.endpoint, t, n, d);
|
|
69
|
+
return await T(p, this.createOptions(r, u));
|
|
70
|
+
}
|
|
71
|
+
async fetchBelongsTo(t, n, d, r, u) {
|
|
72
|
+
const p = O(this.endpoint, t, n, d);
|
|
73
|
+
return await T(p, this.createOptions(r, u));
|
|
74
|
+
}
|
|
75
|
+
async post(t, n) {
|
|
76
|
+
const d = O(this.endpoint, t.type), u = JSON.stringify({
|
|
79
77
|
data: t
|
|
80
|
-
}),
|
|
81
|
-
return
|
|
78
|
+
}), p = this.createOptions(n, {}, u);
|
|
79
|
+
return p.method = "POST", p.headers.set("Content-Type", "application/vnd.api+json"), await T(d, p);
|
|
82
80
|
}
|
|
83
|
-
async postAtomic(t,
|
|
84
|
-
const
|
|
85
|
-
return
|
|
81
|
+
async postAtomic(t, n = {}) {
|
|
82
|
+
const d = new URL([this.endpoint, "operations"].join("/")).href;
|
|
83
|
+
return n.body = JSON.stringify(t), await C(d, n);
|
|
86
84
|
}
|
|
87
85
|
}
|
|
88
|
-
function
|
|
89
|
-
return
|
|
86
|
+
function F(o) {
|
|
87
|
+
return o.replace(/[-][a-z\u00E0-\u00F6\u00F8-\u00FE]/g, (t) => t.slice(1).toUpperCase());
|
|
90
88
|
}
|
|
91
|
-
var L = /* @__PURE__ */ ((
|
|
92
|
-
function
|
|
93
|
-
|
|
89
|
+
var L = /* @__PURE__ */ ((o) => (o[o.HasMany = 0] = "HasMany", o[o.BelongsTo = 1] = "BelongsTo", o))(L || {});
|
|
90
|
+
function A(o, t, n) {
|
|
91
|
+
o[t] = n;
|
|
94
92
|
}
|
|
95
|
-
function
|
|
96
|
-
const t = { type:
|
|
97
|
-
return
|
|
93
|
+
function x(o) {
|
|
94
|
+
const t = { type: o.type };
|
|
95
|
+
return o.lid ? t.lid = o.lid : o.id && (t.id = o.id), t;
|
|
98
96
|
}
|
|
99
|
-
function I(
|
|
100
|
-
const
|
|
101
|
-
for (const
|
|
102
|
-
|
|
103
|
-
function
|
|
104
|
-
return
|
|
105
|
-
}
|
|
106
|
-
function
|
|
107
|
-
const s =
|
|
97
|
+
function I(o, t) {
|
|
98
|
+
const n = t ?? new J(o.endpoint), d = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
|
|
99
|
+
for (const e of o.modelDefinitions)
|
|
100
|
+
d.set(e.type, e), e.relationships && r.set(e.type, e.relationships);
|
|
101
|
+
function u(e) {
|
|
102
|
+
return o.kebabCase ? F(e) : e;
|
|
103
|
+
}
|
|
104
|
+
function p(e) {
|
|
105
|
+
const s = r.get(e.type), l = x(e);
|
|
108
106
|
l.attributes = {}, s && (l.relationships = {});
|
|
109
|
-
for (const [
|
|
110
|
-
if (!(
|
|
111
|
-
if (s &&
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
const
|
|
115
|
-
l.relationships[
|
|
116
|
-
data:
|
|
107
|
+
for (const [a, c] of Object.entries(e))
|
|
108
|
+
if (!(a === "id" || a === "lid" || a === "type" || c === void 0))
|
|
109
|
+
if (s && a in s && l.relationships) {
|
|
110
|
+
const w = s[a];
|
|
111
|
+
if (w.relationshipType === 0) {
|
|
112
|
+
const f = c;
|
|
113
|
+
l.relationships[a] = {
|
|
114
|
+
data: f.map(x)
|
|
117
115
|
};
|
|
118
|
-
} else if (
|
|
119
|
-
const
|
|
120
|
-
l.relationships[
|
|
121
|
-
data:
|
|
116
|
+
} else if (w.relationshipType === 1) {
|
|
117
|
+
const f = c;
|
|
118
|
+
l.relationships[a] = {
|
|
119
|
+
data: x(f)
|
|
122
120
|
};
|
|
123
121
|
} else
|
|
124
|
-
throw new Error(`Unknown relationship type for ${
|
|
122
|
+
throw new Error(`Unknown relationship type for ${a}`);
|
|
125
123
|
} else
|
|
126
|
-
l.attributes[
|
|
124
|
+
l.attributes[a] = c;
|
|
127
125
|
return l;
|
|
128
126
|
}
|
|
129
|
-
function
|
|
130
|
-
if (!
|
|
131
|
-
const
|
|
132
|
-
if (
|
|
133
|
-
const
|
|
134
|
-
for (const [
|
|
135
|
-
|
|
136
|
-
return
|
|
127
|
+
function y(e, s) {
|
|
128
|
+
if (!d.get(e)) throw new Error(`Model type ${e} not defined`);
|
|
129
|
+
const a = s.id ?? crypto.randomUUID(), c = { id: a, type: e, ...s };
|
|
130
|
+
if (o.kebabCase) {
|
|
131
|
+
const w = { id: a, type: e };
|
|
132
|
+
for (const [f, m] of Object.entries(s))
|
|
133
|
+
f !== "id" && m !== void 0 && (w[u(f)] = m);
|
|
134
|
+
return w;
|
|
137
135
|
}
|
|
138
|
-
return
|
|
136
|
+
return c;
|
|
139
137
|
}
|
|
140
|
-
function g(
|
|
141
|
-
function l(
|
|
142
|
-
return
|
|
143
|
-
id:
|
|
144
|
-
...
|
|
138
|
+
function g(e, s) {
|
|
139
|
+
function l(i) {
|
|
140
|
+
return y(i.type, {
|
|
141
|
+
id: i.id,
|
|
142
|
+
...i.attributes
|
|
145
143
|
});
|
|
146
144
|
}
|
|
147
|
-
function i
|
|
148
|
-
|
|
145
|
+
function a(i, h) {
|
|
146
|
+
i.has(h.type) || i.set(h.type, /* @__PURE__ */ new Map()), i.get(h.type)?.set(h.id, h);
|
|
149
147
|
}
|
|
150
|
-
function
|
|
148
|
+
function c(i, h) {
|
|
151
149
|
if (h.id === void 0) throw new Error("Resource identifier must have an id");
|
|
152
|
-
return
|
|
150
|
+
return i.has(h.type) || i.set(h.type, /* @__PURE__ */ new Map()), i.get(h.type)?.get(h.id);
|
|
153
151
|
}
|
|
154
|
-
const
|
|
155
|
-
if (s) for (const
|
|
156
|
-
const
|
|
157
|
-
for (const
|
|
158
|
-
function
|
|
159
|
-
const h =
|
|
152
|
+
const w = /* @__PURE__ */ new Map();
|
|
153
|
+
if (s) for (const i of s) a(w, l(i));
|
|
154
|
+
const f = e.map(l), m = /* @__PURE__ */ new Map();
|
|
155
|
+
for (const i of f) a(m, i);
|
|
156
|
+
function D(i) {
|
|
157
|
+
const h = c(m, i) ?? c(w, i);
|
|
160
158
|
if (!h) throw new Error("Unexpected not found record");
|
|
161
|
-
if (!
|
|
162
|
-
const
|
|
163
|
-
if (
|
|
164
|
-
for (const [
|
|
165
|
-
const
|
|
166
|
-
if (!
|
|
167
|
-
const
|
|
168
|
-
|
|
159
|
+
if (!i.relationships) return;
|
|
160
|
+
const R = r.get(i.type);
|
|
161
|
+
if (R)
|
|
162
|
+
for (const [E, $] of Object.entries(i.relationships)) {
|
|
163
|
+
const k = u(E), M = R[k];
|
|
164
|
+
if (!M || !$.data) continue;
|
|
165
|
+
const z = (M.relationshipType === 0 ? $.data : [$.data]).filter((j) => j && j.type === M.type).map((j) => c(w, j) || c(m, j)).filter(Boolean);
|
|
166
|
+
A(
|
|
169
167
|
h,
|
|
170
|
-
|
|
171
|
-
|
|
168
|
+
k,
|
|
169
|
+
M.relationshipType === 0 ? z : z[0]
|
|
172
170
|
);
|
|
173
171
|
}
|
|
174
172
|
}
|
|
175
173
|
if (s) {
|
|
176
|
-
for (const
|
|
177
|
-
for (const
|
|
174
|
+
for (const i of e) D(i);
|
|
175
|
+
for (const i of s) D(i);
|
|
178
176
|
}
|
|
179
|
-
return
|
|
177
|
+
return f;
|
|
180
178
|
}
|
|
181
|
-
async function
|
|
182
|
-
const
|
|
183
|
-
return { doc:
|
|
179
|
+
async function b(e, s, l) {
|
|
180
|
+
const a = await n.fetchDocument(e, void 0, s, l), c = a.data, w = g(c, a.included);
|
|
181
|
+
return { doc: a, records: w };
|
|
184
182
|
}
|
|
185
|
-
async function
|
|
186
|
-
const
|
|
183
|
+
async function v(e, s, l, a) {
|
|
184
|
+
const c = await n.fetchDocument(e, s, l, a), w = c.data, m = g([w], c.included)[0];
|
|
187
185
|
if (!m) throw new Error(`Record with id ${s} not found`);
|
|
188
186
|
return m;
|
|
189
187
|
}
|
|
190
|
-
async function
|
|
191
|
-
const
|
|
192
|
-
if (!
|
|
193
|
-
const
|
|
194
|
-
if (!
|
|
195
|
-
if (
|
|
196
|
-
const h = await
|
|
197
|
-
id:
|
|
198
|
-
...
|
|
188
|
+
async function H(e, s, l, a) {
|
|
189
|
+
const c = e.type, w = r.get(c);
|
|
190
|
+
if (!w) throw new Error(`Model ${c} has no relationships`);
|
|
191
|
+
const f = w[s];
|
|
192
|
+
if (!f) throw new Error(`Relationship ${s} not defined`);
|
|
193
|
+
if (f.relationshipType === 1) {
|
|
194
|
+
const h = await n.fetchBelongsTo(c, e.id, s, l, a), R = h.data, E = y(f.type, {
|
|
195
|
+
id: R.id,
|
|
196
|
+
...R.attributes
|
|
199
197
|
});
|
|
200
|
-
return
|
|
198
|
+
return A(e, s, E), h;
|
|
201
199
|
}
|
|
202
|
-
const m = await
|
|
203
|
-
(h) =>
|
|
200
|
+
const m = await n.fetchHasMany(c, e.id, s, l, a), i = (f.relationshipType === 0 ? m.data : [m.data]).map(
|
|
201
|
+
(h) => y(f.type, {
|
|
204
202
|
id: h.id,
|
|
205
203
|
...h.attributes
|
|
206
204
|
})
|
|
207
205
|
);
|
|
208
|
-
return
|
|
209
|
-
|
|
206
|
+
return A(
|
|
207
|
+
e,
|
|
210
208
|
s,
|
|
211
|
-
|
|
209
|
+
f.relationshipType === 0 ? i : i[0]
|
|
212
210
|
), m;
|
|
213
211
|
}
|
|
214
|
-
async function
|
|
215
|
-
const l =
|
|
216
|
-
return g([
|
|
212
|
+
async function S(e, s) {
|
|
213
|
+
const l = p(e), a = await n.post(l, s);
|
|
214
|
+
return g([a.data])[0];
|
|
217
215
|
}
|
|
218
|
-
async function
|
|
219
|
-
const
|
|
220
|
-
"atomic:operations":
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
216
|
+
async function B(e, s) {
|
|
217
|
+
const a = {
|
|
218
|
+
"atomic:operations": e.map((f) => {
|
|
219
|
+
const m = { op: f.op };
|
|
220
|
+
return f.data && (m.data = p(f.data)), f.ref && (m.ref = f.ref), m;
|
|
221
|
+
})
|
|
222
|
+
}, c = await n.postAtomic(a, s);
|
|
223
|
+
if (!c) return;
|
|
224
|
+
const w = c["atomic:results"] ? g(c["atomic:results"].map((f) => f.data)) : [];
|
|
225
|
+
return { doc: c, records: w };
|
|
225
226
|
}
|
|
226
227
|
return {
|
|
227
|
-
findAll:
|
|
228
|
-
findRecord:
|
|
229
|
-
findRelated:
|
|
230
|
-
createRecord:
|
|
231
|
-
saveRecord:
|
|
232
|
-
saveAtomic:
|
|
228
|
+
findAll: b,
|
|
229
|
+
findRecord: v,
|
|
230
|
+
findRelated: H,
|
|
231
|
+
createRecord: y,
|
|
232
|
+
saveRecord: S,
|
|
233
|
+
saveAtomic: B
|
|
233
234
|
};
|
|
234
235
|
}
|
|
235
236
|
export {
|
|
236
237
|
L as RelationshipType,
|
|
237
|
-
|
|
238
|
+
F as camel,
|
|
238
239
|
I as useJsonApi
|
|
239
240
|
};
|
|
240
241
|
//# sourceMappingURL=lib.js.map
|
package/dist/lib.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\n\nfunction resolvePath(...segments: string[]): string {\n return new URL(segments.join('/')).href\n}\n\nexport interface PageOption {\n size?: number\n number?: number\n}\n\nexport interface FetchOptions {\n fields?: Record<string, string[]>\n page?: PageOption\n include?: string[]\n filter?: string\n headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nclass HttpError extends Error {\n constructor(\n message: string,\n public status: number,\n public document?: JsonApiDocument,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n\nasync function tryError(response: Response) {\n if (response.ok) return\n let errorMessage = `HTTP error! status: ${response.status} ${response.statusText}`\n let errorDocument: JsonApiDocument | undefined\n try {\n errorDocument = (await response.json()) as JsonApiDocument\n if (errorDocument.errors && errorDocument.errors.length > 0) {\n const firstError = errorDocument.errors[0]\n errorMessage += ` - ${firstError.title}: ${firstError.detail ?? ''}`\n }\n } catch {\n // Ignore JSON parsing errors\n }\n throw new HttpError(errorMessage, response.status, errorDocument)\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n tryError(response)\n const data = (await response.json()) as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n tryError(response)\n if (response.status === 204) return\n const data = (await response.json()) as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\n if (options.fields)\n for (const [key, value] of Object.entries(options.fields)) searchParams.append(`fields[${key}]`, value.join(','))\n if (options.page?.size) searchParams.append('page[size]', options.page.size.toString())\n if (options.page?.number) searchParams.append('page[number]', options.page.number.toString())\n if (options.include) searchParams.append('include', options.include.join(','))\n if (options.filter) searchParams.append('filter', options.filter)\n for (const [key, value] of Object.entries(params)) searchParams.append(key, value)\n return requestOptions\n }\n async fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams) {\n const segments = [this.endpoint, type]\n if (id) segments.push(id)\n const url = resolvePath(...segments)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\n const resources = doc.data as JsonApiResource[]\n return resources\n }\n async fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id)\n const doc = await req(url, this.createOptions(options, params))\n const resource = doc.data as JsonApiResource\n return resource\n }\n async fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = (await req(url, newOptions)) as JsonApiDocument\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options: FetchOptions = {}) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\n }\n}\n","/**\n * Convert str from kebab-case to camelCase\n */\nexport function camel(str: string) {\n return str.replace(/[-][a-z\\u00E0-\\u00F6\\u00F8-\\u00FE]/g, (match) => match.slice(1).toUpperCase())\n}\n","import { type FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiReference extends JsonApiResourceIdentifier {\n relationship?: string\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: JsonApiResource | JsonApiResourceIdentifier[]\n ref?: JsonApiReference\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n 'atomic:operations'?: JsonApiAtomicOperation[]\n 'atomic:results'?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: BaseEntity\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\n /**\n * The URL for the JSON:API endpoint\n */\n endpoint: string\n /**\n * Model definitions for the store\n */\n modelDefinitions: ModelDefinition[]\n /**\n * Whether to convert kebab-case names from JSON:API (older convention) to camelCase\n */\n kebabCase?: boolean\n}\n\nexport enum RelationshipType {\n HasMany = 0,\n BelongsTo = 1,\n}\n\n/**\n * Relationship definition\n */\nexport interface Relationship {\n /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nfunction serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n}\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships && resource.relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships[key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships[key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record\n }\n\n function resourcesToRecords(resources: JsonApiResource[], included?: JsonApiResource[]): BaseEntity[] {\n function resourceToRecord(resource: JsonApiResource): BaseEntity {\n return createRecord(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n }\n\n function setRecord(map: Map<string, Map<string, BaseEntity>>, record: BaseEntity) {\n if (!map.has(record.type)) map.set(record.type, new Map())\n map.get(record.type)?.set(record.id, record)\n }\n\n function getRecord(map: Map<string, Map<string, BaseEntity>>, rid: JsonApiResourceIdentifier) {\n if (rid.id === undefined) throw new Error('Resource identifier must have an id')\n if (!map.has(rid.type)) map.set(rid.type, new Map())\n return map.get(rid.type)?.get(rid.id)\n }\n\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) for (const resource of included) setRecord(includedMap, resourceToRecord(resource))\n\n const records = resources.map(resourceToRecord)\n const recordsMap = new Map<string, Map<string, BaseEntity>>()\n for (const record of records) setRecord(recordsMap, record)\n\n function populateRelationships(resource: JsonApiResource) {\n const record = getRecord(recordsMap, resource) ?? getRecord(includedMap, resource)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue\n if (!reldoc.data) continue\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => getRecord(includedMap, d) || getRecord(recordsMap, d))\n .filter(Boolean)\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n for (const r of resources) populateRelationships(r)\n for (const r of included) populateRelationships(r)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(resources, doc.included) as T[]\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords([resource], doc.included) as T[]\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => ({ op: op.op, data: serialize(op.data) }) as JsonApiAtomicOperation)\n const atomicDoc: JsonApiAtomicDocument = {\n 'atomic:operations': atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = doc['atomic:results'] ? resourcesToRecords(doc['atomic:results'].map((r) => r.data)) : []\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","HttpError","message","status","document","tryError","response","errorMessage","errorDocument","firstError","req","url","options","headers","searchParams","method","signal","body","textSearchParams","finalUrl","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","serializeRid","entity","rid","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","resourceToRecord","setRecord","map","getRecord","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","r","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","saveRecord","saveAtomic","operations","atomicDoc","op"],"mappings":"AAEA,SAASA,KAAeC,GAA4B;AAClD,SAAO,IAAI,IAAIA,EAAS,KAAK,GAAG,CAAC,EAAE;AACrC;AA6BA,MAAMC,UAAkB,MAAM;AAAA,EAC5B,YACEC,GACOC,GACAC,GACP;AACA,UAAMF,CAAO,GAHN,KAAA,SAAAC,GACA,KAAA,WAAAC,GAGP,KAAK,OAAO;AAAA,EACd;AACF;AAEA,eAAeC,EAASC,GAAoB;AAC1C,MAAIA,EAAS,GAAI;AACjB,MAAIC,IAAe,uBAAuBD,EAAS,MAAM,IAAIA,EAAS,UAAU,IAC5EE;AACJ,MAAI;AAEF,QADAA,IAAiB,MAAMF,EAAS,KAAA,GAC5BE,EAAc,UAAUA,EAAc,OAAO,SAAS,GAAG;AAC3D,YAAMC,IAA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IACA,YAAA0B;AAAA,IACA,YAAAC;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\n\nfunction resolvePath(...segments: string[]): string {\n return new URL(segments.join('/')).href\n}\n\nexport interface PageOption {\n size?: number\n number?: number\n}\n\nexport interface FetchOptions {\n fields?: Record<string, string[]>\n page?: PageOption\n include?: string[]\n filter?: string\n headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nclass HttpError extends Error {\n constructor(\n message: string,\n public status: number,\n public body?: unknown,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n\nasync function tryJson(response: Response) {\n try {\n return await response.json()\n } catch {\n // Ignore JSON parsing errors\n }\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n const responseBody = await tryJson(response)\n if (!response.ok)\n throw new HttpError(`HTTP error! status: ${response.status} ${response.statusText}`, response.status, responseBody)\n const data = responseBody as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n const responseBody = await tryJson(response)\n if (!response.ok)\n throw new HttpError(`HTTP error! status: ${response.status} ${response.statusText}`, response.status, responseBody)\n if (response.status === 204) return\n const data = responseBody as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\n if (options.fields)\n for (const [key, value] of Object.entries(options.fields)) searchParams.append(`fields[${key}]`, value.join(','))\n if (options.page?.size) searchParams.append('page[size]', options.page.size.toString())\n if (options.page?.number) searchParams.append('page[number]', options.page.number.toString())\n if (options.include) searchParams.append('include', options.include.join(','))\n if (options.filter) searchParams.append('filter', options.filter)\n for (const [key, value] of Object.entries(params)) searchParams.append(key, value)\n return requestOptions\n }\n async fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams) {\n const segments = [this.endpoint, type]\n if (id) segments.push(id)\n const url = resolvePath(...segments)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\n const resources = doc.data as JsonApiResource[]\n return resources\n }\n async fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id)\n const doc = await req(url, this.createOptions(options, params))\n const resource = doc.data as JsonApiResource\n return resource\n }\n async fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = await req(url, newOptions)\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options: FetchOptions = {}) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\n }\n}\n","/**\n * Convert str from kebab-case to camelCase\n */\nexport function camel(str: string) {\n return str.replace(/[-][a-z\\u00E0-\\u00F6\\u00F8-\\u00FE]/g, (match) => match.slice(1).toUpperCase())\n}\n","import { type FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiReference extends JsonApiResourceIdentifier {\n relationship?: string\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: JsonApiResource | JsonApiResourceIdentifier[]\n ref?: JsonApiReference\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n 'atomic:operations'?: JsonApiAtomicOperation[]\n 'atomic:results'?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: BaseEntity\n ref?: JsonApiReference\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\n /**\n * The URL for the JSON:API endpoint\n */\n endpoint: string\n /**\n * Model definitions for the store\n */\n modelDefinitions: ModelDefinition[]\n /**\n * Whether to convert kebab-case names from JSON:API (older convention) to camelCase\n */\n kebabCase?: boolean\n}\n\nexport enum RelationshipType {\n HasMany = 0,\n BelongsTo = 1,\n}\n\n/**\n * Relationship definition\n */\nexport interface Relationship {\n /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nfunction serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n}\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships && resource.relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships[key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships[key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record\n }\n\n function resourcesToRecords(resources: JsonApiResource[], included?: JsonApiResource[]): BaseEntity[] {\n function resourceToRecord(resource: JsonApiResource): BaseEntity {\n return createRecord(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n }\n\n function setRecord(map: Map<string, Map<string, BaseEntity>>, record: BaseEntity) {\n if (!map.has(record.type)) map.set(record.type, new Map())\n map.get(record.type)?.set(record.id, record)\n }\n\n function getRecord(map: Map<string, Map<string, BaseEntity>>, rid: JsonApiResourceIdentifier) {\n if (rid.id === undefined) throw new Error('Resource identifier must have an id')\n if (!map.has(rid.type)) map.set(rid.type, new Map())\n return map.get(rid.type)?.get(rid.id)\n }\n\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) for (const resource of included) setRecord(includedMap, resourceToRecord(resource))\n\n const records = resources.map(resourceToRecord)\n const recordsMap = new Map<string, Map<string, BaseEntity>>()\n for (const record of records) setRecord(recordsMap, record)\n\n function populateRelationships(resource: JsonApiResource) {\n const record = getRecord(recordsMap, resource) ?? getRecord(includedMap, resource)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue\n if (!reldoc.data) continue\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => getRecord(includedMap, d) || getRecord(recordsMap, d))\n .filter(Boolean)\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n for (const r of resources) populateRelationships(r)\n for (const r of included) populateRelationships(r)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(resources, doc.included) as T[]\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords([resource], doc.included) as T[]\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => {\n const jsonApiOp: JsonApiAtomicOperation = { op: op.op }\n if (op.data) jsonApiOp.data = serialize(op.data)\n if (op.ref) jsonApiOp.ref = op.ref\n return jsonApiOp\n })\n const atomicDoc: JsonApiAtomicDocument = {\n 'atomic:operations': atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = doc['atomic:results'] ? resourcesToRecords(doc['atomic:results'].map((r) => r.data)) : []\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","HttpError","message","status","body","tryJson","response","req","url","options","headers","searchParams","method","signal","textSearchParams","finalUrl","responseBody","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","serializeRid","entity","rid","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","resourceToRecord","setRecord","map","getRecord","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","r","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","saveRecord","saveAtomic","operations","atomicDoc","op","jsonApiOp"],"mappings":"AAEA,SAASA,KAAeC,GAA4B;AAClD,SAAO,IAAI,IAAIA,EAAS,KAAK,GAAG,CAAC,EAAE;AACrC;AA6BA,MAAMC,UAAkB,MAAM;AAAA,EAC5B,YACEC,GACOC,GACAC,GACP;AACA,UAAMF,CAAO,GAHN,KAAA,SAAAC,GACA,KAAA,OAAAC,GAGP,KAAK,OAAO;AAAA,EACd;AACF;AAEA,eAAeC,EAAQC,GAAoB;AACzC,MAAI;AACF,WAAO,MAAMA,EAAS,KAAA;AAAA,EACxB,QAAQ;AAAA,EAER;AACF;AAEA,eAAeC,EAAIC,GAAaC,GAAkB;AAChD,QAAM,E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