monorise 1.14.1 → 1.15.0-dev.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.
@@ -1,38 +1,640 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
- var __async = (__this, __arguments, generator) => {
18
- return new Promise((resolve, reject) => {
19
- var fulfilled = (value) => {
20
- try {
21
- step(generator.next(value));
22
- } catch (e) {
23
- reject(e);
1
+ // proxy/operations.ts
2
+ var hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ var notFound = (message) => ({
5
+ ok: false,
6
+ status: 404,
7
+ message
8
+ });
9
+ var invalid = (message) => ({
10
+ ok: false,
11
+ status: 400,
12
+ message
13
+ });
14
+ var asEntityType = (entityConfig, byEntityType, entityType) => {
15
+ const declared = (from, to) => {
16
+ const fields = entityConfig && hasOwn(entityConfig, from) ? entityConfig[from].mutual?.mutualFields : void 0;
17
+ return Object.values(fields ?? {}).find(
18
+ (field) => field.entityType === to && field.mutual
19
+ )?.mutual?.asEntity?.name;
20
+ };
21
+ return declared(byEntityType, entityType) ?? declared(entityType, byEntityType);
22
+ };
23
+ var relationshipCreate = (entityConfig, relationship, requestedAsEntity) => {
24
+ const { byEntityType, byEntityId, entityType, entityId, payload } = relationship;
25
+ const asEntity = requestedAsEntity || asEntityType(entityConfig, byEntityType, entityType);
26
+ if (!asEntity) return [relationship];
27
+ return [
28
+ relationship,
29
+ {
30
+ kind: "entity",
31
+ action: "create",
32
+ entityType: asEntity,
33
+ ...payload === void 0 ? {} : { payload },
34
+ asEntityOf: { byEntityType, byEntityId, entityType, entityId },
35
+ ...relationship.operationIndex === void 0 ? {} : { operationIndex: relationship.operationIndex }
36
+ }
37
+ ];
38
+ };
39
+ var relationshipFieldOperations = (entityConfig, entityType, entityId, payload, write, operationIndex) => {
40
+ const config = entityConfig && hasOwn(entityConfig, entityType) ? entityConfig[entityType] : void 0;
41
+ const fields = config?.mutual?.mutualFields;
42
+ if (!payload || !fields) return [];
43
+ const operations = [];
44
+ for (const [field, value] of Object.entries(payload)) {
45
+ if (!hasOwn(fields, field)) continue;
46
+ const base = {
47
+ kind: "relationship",
48
+ byEntityType: entityType,
49
+ byEntityId: entityId,
50
+ entityType: fields[field].entityType,
51
+ ...operationIndex === void 0 ? {} : { operationIndex }
52
+ };
53
+ const ids = Array.isArray(value) ? value.filter((id) => typeof id === "string") : [];
54
+ for (const id of ids) {
55
+ operations.push(
56
+ ...relationshipCreate(entityConfig, {
57
+ ...base,
58
+ action: "create",
59
+ entityId: id
60
+ })
61
+ );
62
+ }
63
+ if (write === "update") operations.push({ ...base, action: "delete" });
64
+ }
65
+ return operations;
66
+ };
67
+ var entityWrite = (entityConfig, actions, entityType, entityId, payload, operationIndex) => {
68
+ const index = operationIndex === void 0 ? {} : { operationIndex };
69
+ return [
70
+ ...actions.map(
71
+ (action) => ({
72
+ kind: "entity",
73
+ action,
74
+ entityType,
75
+ ...entityId === void 0 ? {} : { entityId },
76
+ ...payload === void 0 ? {} : { payload },
77
+ ...index
78
+ })
79
+ ),
80
+ ...relationshipFieldOperations(
81
+ entityConfig,
82
+ entityType,
83
+ entityId,
84
+ payload,
85
+ // An upsert can update, so its relationship fields count as an update's.
86
+ actions.includes("update") ? "update" : "create",
87
+ operationIndex
88
+ )
89
+ ];
90
+ };
91
+ var transactionOperations = (entityConfig, body) => {
92
+ const entries = isRecord(body) ? body.operations : void 0;
93
+ if (!Array.isArray(entries)) {
94
+ return invalid('Request body must contain an "operations" array');
95
+ }
96
+ const operations = [];
97
+ for (const [operationIndex, entry] of entries.entries()) {
98
+ if (!isRecord(entry) || typeof entry.entityType !== "string") {
99
+ return invalid(`Operation ${operationIndex} has no entityType`);
100
+ }
101
+ const { entityType } = entry;
102
+ const entityId = typeof entry.entityId === "string" ? entry.entityId : void 0;
103
+ const payload = isRecord(entry.payload) ? entry.payload : void 0;
104
+ switch (entry.operation) {
105
+ case "createEntity":
106
+ case "updateEntity":
107
+ operations.push(
108
+ ...entityWrite(
109
+ entityConfig,
110
+ [entry.operation === "createEntity" ? "create" : "update"],
111
+ entityType,
112
+ entityId,
113
+ payload,
114
+ operationIndex
115
+ )
116
+ );
117
+ break;
118
+ case "adjustEntity":
119
+ operations.push({
120
+ kind: "entity",
121
+ action: "adjust",
122
+ entityType,
123
+ ...entityId === void 0 ? {} : { entityId },
124
+ ...isRecord(entry.adjustments) ? { adjustments: entry.adjustments } : {},
125
+ operationIndex
126
+ });
127
+ break;
128
+ case "deleteEntity":
129
+ operations.push({
130
+ kind: "entity",
131
+ action: "delete",
132
+ entityType,
133
+ ...entityId === void 0 ? {} : { entityId },
134
+ operationIndex
135
+ });
136
+ break;
137
+ case "createMutual":
138
+ case "updateMutual":
139
+ case "deleteMutual": {
140
+ if (typeof entry.byEntityType !== "string" || typeof entry.byEntityId !== "string") {
141
+ return invalid(
142
+ `Operation ${operationIndex} needs byEntityType and byEntityId`
143
+ );
144
+ }
145
+ const relationship = {
146
+ kind: "relationship",
147
+ action: entry.operation === "createMutual" ? "create" : entry.operation === "updateMutual" ? "update" : "delete",
148
+ byEntityType: entry.byEntityType,
149
+ byEntityId: entry.byEntityId,
150
+ entityType,
151
+ ...entityId === void 0 ? {} : { entityId },
152
+ ...payload === void 0 ? {} : { payload },
153
+ operationIndex
154
+ };
155
+ operations.push(
156
+ ...relationship.action === "create" ? relationshipCreate(entityConfig, relationship) : [relationship]
157
+ );
158
+ break;
24
159
  }
160
+ default:
161
+ return invalid(
162
+ `Operation ${operationIndex} has an unknown operation '${String(entry.operation)}'`
163
+ );
164
+ }
165
+ }
166
+ return { ok: true, operations };
167
+ };
168
+ var decode = (segment) => {
169
+ try {
170
+ return decodeURIComponent(segment);
171
+ } catch {
172
+ return void 0;
173
+ }
174
+ };
175
+ var parseOperations = ({
176
+ method,
177
+ path,
178
+ searchParams,
179
+ body,
180
+ entityConfig
181
+ }) => {
182
+ const decoded = (path === "/" ? [] : path.split("/").slice(1)).map(decode);
183
+ if (decoded.some((segment) => !segment || segment.includes("/"))) {
184
+ return invalid("Malformed path");
185
+ }
186
+ const [root, ...rest] = decoded;
187
+ const verb = method.toUpperCase();
188
+ const payload = isRecord(body) ? body : void 0;
189
+ const unknown = notFound(`Monorise Core has no route ${verb} ${path}`);
190
+ const one = (operation) => ({
191
+ ok: true,
192
+ operations: [operation]
193
+ });
194
+ const params = (...names) => Object.fromEntries(
195
+ names.flatMap((name) => {
196
+ const value = searchParams.get(name);
197
+ return value ? [[name, value]] : [];
198
+ })
199
+ );
200
+ if (root === "entity") {
201
+ const [entityType, second, third, fourth] = rest;
202
+ if (rest.length === 1 && verb === "GET") {
203
+ return one({
204
+ kind: "entity",
205
+ action: "list",
206
+ entityType,
207
+ ...params("query", "start", "end")
208
+ });
209
+ }
210
+ if (rest.length === 1 && verb === "POST") {
211
+ const entityId = typeof payload?.entityId === "string" ? payload.entityId : void 0;
212
+ return {
213
+ ok: true,
214
+ operations: entityWrite(
215
+ entityConfig,
216
+ ["create"],
217
+ entityType,
218
+ entityId,
219
+ payload
220
+ )
221
+ };
222
+ }
223
+ if (rest.length === 4 && second === "unique" && verb === "GET") {
224
+ return one({
225
+ kind: "entity",
226
+ action: "get",
227
+ entityType,
228
+ unique: { field: third, value: fourth }
229
+ });
230
+ }
231
+ if (rest.length === 3 && third === "adjust" && verb === "POST") {
232
+ const { $condition: _, ...adjustments } = payload ?? {};
233
+ return one({
234
+ kind: "entity",
235
+ action: "adjust",
236
+ entityType,
237
+ entityId: second,
238
+ ...payload === void 0 ? {} : { adjustments }
239
+ });
240
+ }
241
+ if (rest.length === 2) {
242
+ const write = (actions, data = payload) => ({
243
+ ok: true,
244
+ operations: entityWrite(
245
+ entityConfig,
246
+ actions,
247
+ entityType,
248
+ second,
249
+ data
250
+ )
251
+ });
252
+ if (verb === "GET") {
253
+ return one({
254
+ kind: "entity",
255
+ action: "get",
256
+ entityType,
257
+ entityId: second
258
+ });
259
+ }
260
+ if (verb === "PUT") return write(["create", "update"]);
261
+ if (verb === "PATCH") {
262
+ if (payload === void 0) return write(["update"]);
263
+ const { $condition: _, $where: __, ...data } = payload;
264
+ return write(["update"], data);
265
+ }
266
+ if (verb === "DELETE") {
267
+ return one({
268
+ kind: "entity",
269
+ action: "delete",
270
+ entityType,
271
+ entityId: second
272
+ });
273
+ }
274
+ }
275
+ return unknown;
276
+ }
277
+ if (root === "mutual") {
278
+ const [byEntityType, byEntityId, entityType, entityId] = rest;
279
+ if (rest.length === 3 && verb === "GET") {
280
+ const chain = searchParams.get("chainEntityQuery");
281
+ const types = [
282
+ byEntityType,
283
+ ...chain ? chain.split(",") : [],
284
+ entityType
285
+ ];
286
+ return {
287
+ ok: true,
288
+ operations: types.slice(1).map(
289
+ (to, hop) => ({
290
+ kind: "relationship",
291
+ action: "read",
292
+ byEntityType: types[hop],
293
+ ...hop === 0 ? { byEntityId } : {},
294
+ entityType: to
295
+ })
296
+ )
297
+ };
298
+ }
299
+ if (rest.length === 4) {
300
+ const action = verb === "GET" ? "read" : verb === "POST" ? "create" : verb === "PATCH" ? "update" : verb === "DELETE" ? "delete" : void 0;
301
+ if (action) {
302
+ const relationship = {
303
+ kind: "relationship",
304
+ action,
305
+ byEntityType,
306
+ byEntityId,
307
+ entityType,
308
+ entityId,
309
+ ...payload === void 0 || action === "read" || action === "delete" ? {} : { payload }
310
+ };
311
+ return {
312
+ ok: true,
313
+ operations: action === "create" ? (
314
+ // CreateMutualController passes ?asEntity= to the service.
315
+ relationshipCreate(
316
+ entityConfig,
317
+ relationship,
318
+ searchParams.get("asEntity") ?? void 0
319
+ )
320
+ ) : [relationship]
321
+ };
322
+ }
323
+ }
324
+ return unknown;
325
+ }
326
+ if (root === "tag" && rest.length === 2 && verb === "GET") {
327
+ return one({
328
+ kind: "entity",
329
+ action: "list",
330
+ entityType: rest[0],
331
+ tag: rest[1],
332
+ ...params("group", "start", "end")
333
+ });
334
+ }
335
+ if (root === "transaction" && rest.length === 0 && verb === "POST") {
336
+ return transactionOperations(entityConfig, body);
337
+ }
338
+ if (root === "app") {
339
+ return one({
340
+ kind: "route",
341
+ method: verb,
342
+ path: `/${decoded.join("/")}`,
343
+ ...body === void 0 ? {} : { body }
344
+ });
345
+ }
346
+ return unknown;
347
+ };
348
+
349
+ // proxy/rules.ts
350
+ var allow = () => true;
351
+ var deny = () => false;
352
+ var hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
353
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
354
+ var own = (object, key) => isRecord2(object) && hasOwn2(object, key) ? object[key] : void 0;
355
+ var asRule = (value) => typeof value === "function" ? value : void 0;
356
+ var ruleFor = (value, action) => asRule(value) ?? asRule(own(value, action));
357
+ var outranks = (rank, than) => {
358
+ const index = rank.findIndex((value, at) => value !== than[at]);
359
+ return index !== -1 && rank[index] > than[index];
360
+ };
361
+ var matchRoute = (routes, operation) => {
362
+ if (!routes) return void 0;
363
+ const exact = asRule(own(routes, `${operation.method} ${operation.path}`));
364
+ if (exact) return { rule: exact, params: {} };
365
+ const segments = operation.path.split("/").filter(Boolean);
366
+ let best;
367
+ for (const [key, rule] of Object.entries(routes)) {
368
+ const [method, pattern] = key.split(" ");
369
+ if (method !== operation.method || !pattern || typeof rule !== "function") {
370
+ continue;
371
+ }
372
+ const parts = pattern.split("/").filter(Boolean);
373
+ const params = {};
374
+ const rest = parts.at(-1) === "*";
375
+ const fixed = rest ? parts.slice(0, -1) : parts;
376
+ if (rest ? segments.length < fixed.length : segments.length !== fixed.length) {
377
+ continue;
378
+ }
379
+ const matches = fixed.every((part, index) => {
380
+ if (part.startsWith(":")) {
381
+ params[part.slice(1)] = segments[index];
382
+ return true;
383
+ }
384
+ return part === segments[index];
385
+ });
386
+ if (!matches) continue;
387
+ const paramCount = fixed.filter((part) => part.startsWith(":")).length;
388
+ const rank = [fixed.length - paramCount, rest ? 0 : 1, -paramCount];
389
+ if (!best || outranks(rank, best.rank)) {
390
+ best = { match: { rule, params }, rank };
391
+ }
392
+ }
393
+ return best?.match;
394
+ };
395
+ var findRule = (rules, routes, operation) => {
396
+ const tableFallback = own(rules, "*");
397
+ const found = (rule, matched = operation) => rule ? { rule, operation: matched } : void 0;
398
+ if (operation.kind === "entity") {
399
+ const entity = own(rules, operation.entityType);
400
+ return found(
401
+ asRule(entity) ?? asRule(own(entity, operation.action)) ?? asRule(own(entity, "*")) ?? ruleFor(tableFallback, operation.action)
402
+ );
403
+ }
404
+ if (operation.kind === "relationship") {
405
+ const entity = own(rules, operation.byEntityType);
406
+ const mutuals = own(entity, "mutuals");
407
+ return found(
408
+ asRule(entity) ?? ruleFor(own(mutuals, operation.entityType), operation.action) ?? asRule(own(own(mutuals, operation.entityType), "*")) ?? ruleFor(own(mutuals, "*"), operation.action) ?? ruleFor(tableFallback, operation.action)
409
+ );
410
+ }
411
+ const route = matchRoute(routes, operation);
412
+ if (route) return found(route.rule, { ...operation, params: route.params });
413
+ return found(asRule(own(routes, "*")) ?? asRule(tableFallback));
414
+ };
415
+ var describeOperation = (operation) => operation.kind === "entity" ? `${operation.action} on '${operation.entityType}'` : operation.kind === "relationship" ? `${operation.action} on ${operation.byEntityType}\u2192${operation.entityType}` : `${operation.method} ${operation.path}`;
416
+ var missingRuleHint = (operation) => operation.kind === "entity" ? `rules: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => \u2026 } }` : operation.kind === "relationship" ? `rules: { '${operation.byEntityType}': { mutuals: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => \u2026 } } } }` : `routes: { '${operation.method} ${operation.path}': (operation, { session }) => \u2026 }`;
417
+ var forbidden = (message, operation) => new Response(
418
+ JSON.stringify({
419
+ code: "FORBIDDEN",
420
+ message,
421
+ ..."operationIndex" in operation && operation.operationIndex !== void 0 ? { operationIndex: operation.operationIndex } : {}
422
+ }),
423
+ { status: 403, headers: { "content-type": "application/json" } }
424
+ );
425
+ var checkOperations = async ({
426
+ operations,
427
+ rules,
428
+ routes,
429
+ context,
430
+ logMissingRules = false
431
+ }) => {
432
+ for (const operation of operations) {
433
+ const found = findRule(rules, routes, operation);
434
+ if (!found) {
435
+ if (logMissingRules) {
436
+ console.warn(
437
+ `[monorise/proxy] No rule for ${describeOperation(operation)}. Add one: ${missingRuleHint(operation)}`
438
+ );
439
+ }
440
+ return forbidden(
441
+ `No proxy rule for ${describeOperation(operation)}`,
442
+ operation
443
+ );
444
+ }
445
+ const result = await found.rule(found.operation, context);
446
+ if (result instanceof Response) return result;
447
+ if (result !== true) {
448
+ return forbidden(
449
+ `Proxy rule refused ${describeOperation(operation)}`,
450
+ operation
451
+ );
452
+ }
453
+ }
454
+ return void 0;
455
+ };
456
+
457
+ // proxy/handler.ts
458
+ var FORWARDED_HEADERS = [
459
+ "content-type",
460
+ "accept",
461
+ "accept-language",
462
+ "x-request-id"
463
+ ];
464
+ var DROPPED_RESPONSE_HEADERS = [
465
+ "content-encoding",
466
+ "content-length",
467
+ "transfer-encoding",
468
+ "connection"
469
+ ];
470
+ var hasOwn3 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
471
+ var env = (name) => typeof process === "undefined" ? void 0 : process.env?.[name];
472
+ var json = (status, body) => new Response(JSON.stringify(body), {
473
+ status,
474
+ headers: { "content-type": "application/json" }
475
+ });
476
+ var unauthorized = () => json(401, { code: "UNAUTHORIZED", message: "Unauthorized" });
477
+ var misconfigured = (message) => {
478
+ console.error(`[monorise/proxy] ${message}`);
479
+ return json(500, { code: "PROXY_MISCONFIGURED", message });
480
+ };
481
+ var createProxyHandler = (options) => {
482
+ const multiple = options.callers !== void 0 || options.caller !== void 0;
483
+ if (multiple && (typeof options.caller !== "function" || typeof options.callers !== "object" || options.apiKey !== void 0 || options.rules !== void 0 || options.routes !== void 0)) {
484
+ throw new Error(
485
+ "createProxyHandler takes either caller and callers, or apiKey and rules"
486
+ );
487
+ }
488
+ const basePath = `/${(options.basePath ?? "/api/core").replace(/^\/+|\/+$/g, "")}`;
489
+ const entityConfig = options.config?.EntityConfig;
490
+ const logMissingRules = options.logMissingRules ?? env("NODE_ENV") !== "production";
491
+ const coreClient = (apiBaseUrl, apiKey) => {
492
+ const coreFetch = (path, init = {}) => {
493
+ const headers = new Headers(init.headers);
494
+ headers.set("x-api-key", apiKey);
495
+ return fetch(`${apiBaseUrl}/core${path}`, {
496
+ cache: "no-store",
497
+ ...init,
498
+ headers
499
+ });
25
500
  };
26
- var rejected = (value) => {
501
+ return { get: (path) => coreFetch(path), fetch: coreFetch };
502
+ };
503
+ const prepare = async (request) => {
504
+ const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.clone().arrayBuffer();
505
+ const authenticated = options.authenticate ? await options.authenticate(request) : void 0;
506
+ if (authenticated instanceof Response) return authenticated;
507
+ const session = authenticated ?? void 0;
508
+ let caller;
509
+ let entry;
510
+ if (multiple) {
511
+ caller = await options.caller?.({ session, request });
512
+ const callers = options.callers ?? {};
513
+ entry = caller !== void 0 && hasOwn3(callers, caller) ? callers[caller] : void 0;
514
+ } else if (!options.authenticate || session !== void 0) {
515
+ entry = options;
516
+ }
517
+ if (!entry) return unauthorized();
518
+ if (!entry.apiKey) {
519
+ return misconfigured(
520
+ caller === void 0 ? "No apiKey is set" : `No apiKey is set for caller '${caller}'`
521
+ );
522
+ }
523
+ const apiBaseUrl = (options.apiBaseUrl ?? env("API_BASE_URL"))?.replace(
524
+ /\/+$/,
525
+ ""
526
+ );
527
+ if (!apiBaseUrl) {
528
+ return misconfigured("No apiBaseUrl is set, and API_BASE_URL is empty");
529
+ }
530
+ const url = new URL(request.url);
531
+ if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
532
+ return json(404, {
533
+ code: "NOT_FOUND",
534
+ message: `The proxy serves paths under ${basePath}`
535
+ });
536
+ }
537
+ const path = url.pathname.slice(basePath.length) || "/";
538
+ const text = body ? new TextDecoder().decode(body) : "";
539
+ let parsed;
540
+ if (text.trim()) {
27
541
  try {
28
- step(generator.throw(value));
29
- } catch (e) {
30
- reject(e);
542
+ parsed = JSON.parse(text);
543
+ } catch {
544
+ if (!path.startsWith("/app/")) {
545
+ return json(400, {
546
+ code: "BAD_REQUEST",
547
+ message: "Request body must be JSON"
548
+ });
549
+ }
31
550
  }
551
+ }
552
+ const result = parseOperations({
553
+ method: request.method,
554
+ path,
555
+ searchParams: url.searchParams,
556
+ body: parsed,
557
+ entityConfig
558
+ });
559
+ if (!result.ok) {
560
+ return json(result.status, {
561
+ code: result.status === 404 ? "NOT_FOUND" : "BAD_REQUEST",
562
+ message: result.message
563
+ });
564
+ }
565
+ const context = {
566
+ session,
567
+ request,
568
+ core: coreClient(apiBaseUrl, entry.apiKey)
32
569
  };
33
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
- step((generator = generator.apply(__this, __arguments)).next());
35
- });
570
+ const refusal = await checkOperations({
571
+ operations: result.operations,
572
+ rules: entry.rules,
573
+ routes: entry.routes,
574
+ context,
575
+ logMissingRules
576
+ });
577
+ if (refusal) return refusal;
578
+ return {
579
+ caller,
580
+ session,
581
+ apiKey: entry.apiKey,
582
+ apiBaseUrl,
583
+ target: `${path}${url.search}`,
584
+ body: body && body.byteLength > 0 ? body : void 0,
585
+ operations: result.operations
586
+ };
587
+ };
588
+ const checkRequest = async (request) => {
589
+ const prepared = await prepare(request);
590
+ if (prepared instanceof Response) {
591
+ return { allowed: false, response: prepared };
592
+ }
593
+ const { caller, session, operations } = prepared;
594
+ return { allowed: true, caller, session, operations };
595
+ };
596
+ const handle = async (request) => {
597
+ const prepared = await prepare(request);
598
+ if (prepared instanceof Response) return prepared;
599
+ const headers = new Headers();
600
+ for (const name of FORWARDED_HEADERS) {
601
+ const value = request.headers.get(name);
602
+ if (value !== null) headers.set(name, value);
603
+ }
604
+ headers.set("x-api-key", prepared.apiKey);
605
+ let response;
606
+ try {
607
+ response = await fetch(`${prepared.apiBaseUrl}/core${prepared.target}`, {
608
+ method: request.method,
609
+ headers,
610
+ body: prepared.body,
611
+ cache: "no-store"
612
+ });
613
+ } catch (error) {
614
+ console.error("[monorise/proxy] Monorise Core is unreachable", error);
615
+ return json(502, {
616
+ code: "BAD_GATEWAY",
617
+ message: "Monorise Core is unreachable"
618
+ });
619
+ }
620
+ const responseHeaders = new Headers(response.headers);
621
+ for (const name of DROPPED_RESPONSE_HEADERS) responseHeaders.delete(name);
622
+ return new Response(response.body, {
623
+ status: response.status,
624
+ statusText: response.statusText,
625
+ headers: responseHeaders
626
+ });
627
+ };
628
+ const alias = (request) => handle(request);
629
+ return {
630
+ handle,
631
+ checkRequest,
632
+ GET: alias,
633
+ POST: alias,
634
+ PUT: alias,
635
+ PATCH: alias,
636
+ DELETE: alias
637
+ };
36
638
  };
37
639
 
38
640
  // index.ts
@@ -48,21 +650,24 @@ var getApiBaseUrl = () => {
48
650
  var getApiKey = () => {
49
651
  return process.env.MONORISE_API_KEY || process.env.API_KEY || "";
50
652
  };
51
- var generateWebSocketTicket = (options) => __async(null, null, function* () {
653
+ var generateWebSocketTicket = async (options) => {
52
654
  const apiBaseUrl = getApiBaseUrl();
53
655
  const apiKey = getApiKey();
54
656
  const { entityType, entityId, feedTypes } = options;
55
- const response = yield fetch(
657
+ const response = await fetch(
56
658
  // `/core` is monorise's own Hono basePath (packages/core/handles/app.ts),
57
659
  // not part of API_BASE_URL -- the React default endpoint spells the same
58
660
  // path as `/api/core/ws/ticket/...`.
59
661
  `${apiBaseUrl}/core/ws/ticket/${entityType}/${entityId}`,
60
662
  {
61
663
  method: "POST",
62
- headers: __spreadValues({
63
- "Content-Type": "application/json"
64
- }, apiKey && { "x-api-key": apiKey }),
65
- body: JSON.stringify(__spreadValues({}, feedTypes && { feedTypes }))
664
+ headers: {
665
+ "Content-Type": "application/json",
666
+ ...apiKey && { "x-api-key": apiKey }
667
+ },
668
+ body: JSON.stringify({
669
+ ...feedTypes && { feedTypes }
670
+ })
66
671
  }
67
672
  );
68
673
  if (!response.ok) {
@@ -71,8 +676,11 @@ var generateWebSocketTicket = (options) => __async(null, null, function* () {
71
676
  );
72
677
  }
73
678
  return response.json();
74
- });
679
+ };
75
680
  export {
681
+ allow,
682
+ createProxyHandler,
683
+ deny,
76
684
  generateWebSocketTicket
77
685
  };
78
686
  //# sourceMappingURL=index.js.map