@powerhousedao/reactor-api 6.2.3-dev.1 → 6.2.3-dev.100

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.
Files changed (65) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-DdamNLPT.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -24
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CLmTtNJC.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -11
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-54gdI9bu.mjs → adapter-http-express-78KD77cI.mjs} +11 -11
  7. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-DmccBVOe.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +14 -13
  9. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  10. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  11. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  12. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  13. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  14. package/dist/error-info-Cr6oQACe.mjs +601 -0
  15. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  16. package/dist/index.d.mts +3410 -1028
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +7549 -2724
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  21. package/dist/package-subgraph-check-BxKx9kcQ.mjs.map +1 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  23. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  24. package/dist/pglite-node-CcX2YT-l.mjs +744 -0
  25. package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
  26. package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
  27. package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
  28. package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
  29. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  30. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  31. package/dist/src/graphql/subgraph-types.mjs +14 -0
  32. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  33. package/dist/src/packages/https-hooks.d.mts +4 -4
  34. package/dist/src/packages/https-hooks.d.mts.map +1 -1
  35. package/dist/src/packages/https-hooks.mjs +2 -2
  36. package/dist/src/packages/https-hooks.mjs.map +1 -1
  37. package/dist/src/packages/vite-loader.d.mts +30 -9
  38. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  39. package/dist/src/packages/vite-loader.mjs +208 -88
  40. package/dist/src/packages/vite-loader.mjs.map +1 -1
  41. package/dist/src/pglite/pglite-node.d.mts +434 -0
  42. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  43. package/dist/src/pglite/pglite-node.mjs +5 -0
  44. package/dist/src/pglite/worker/entry.d.mts +2 -0
  45. package/dist/src/pglite/worker/entry.mjs +298 -0
  46. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  47. package/dist/subgraph-extraction-C_hFvSaS.mjs +1884 -0
  48. package/dist/subgraph-extraction-C_hFvSaS.mjs.map +1 -0
  49. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  50. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  51. package/dist/types-Bz_xjf8j.d.mts +105 -0
  52. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  53. package/package.json +42 -26
  54. package/dist/adapter-gateway-apollo-DdamNLPT.mjs.map +0 -1
  55. package/dist/adapter-gateway-mercurius-CLmTtNJC.mjs.map +0 -1
  56. package/dist/adapter-http-express-54gdI9bu.mjs.map +0 -1
  57. package/dist/adapter-http-fastify-DmccBVOe.mjs.map +0 -1
  58. package/dist/path-normalize-DWWFLiy6.mjs +0 -23
  59. package/dist/path-normalize-DWWFLiy6.mjs.map +0 -1
  60. package/dist/types-Bz2niABC.d.mts +0 -48
  61. package/dist/types-Bz2niABC.d.mts.map +0 -1
  62. package/dist/utils-XWVecaNn.mjs +0 -653
  63. package/dist/utils-XWVecaNn.mjs.map +0 -1
  64. package/dist/websocket-DncAB9XK.mjs +0 -18
  65. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -1,653 +0,0 @@
1
-
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="df700b05-17ec-5ac9-b31f-f6f9cfcfa5f5")}catch(e){}}();
3
- import { gql } from "graphql-tag";
4
- import { GraphQLError } from "graphql";
5
- import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
6
- import { childLogger } from "document-model";
7
- import path from "node:path";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
9
- //#region src/graphql/errors.ts
10
- /** Caller (authenticated or anonymous) lacks permission for the document. */
11
- var ForbiddenError = class extends GraphQLError {
12
- constructor(detail = "") {
13
- const base = DRIVE_AUTH_ERROR_MESSAGES.forbidden;
14
- super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "FORBIDDEN" } });
15
- }
16
- };
17
- /** Anonymous caller on an action that requires logging in. */
18
- var AuthenticationRequiredError = class extends GraphQLError {
19
- constructor(detail = "") {
20
- const base = DRIVE_AUTH_ERROR_MESSAGES.authenticationRequired;
21
- super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "UNAUTHENTICATED" } });
22
- }
23
- };
24
- /**
25
- * The reactor holds no decision model, so no authorization preflight can be
26
- * answered.
27
- *
28
- * Distinct from a denial, and deliberately so: a caller that cannot get a
29
- * prediction should render its controls as it did before it asked and let the
30
- * submit path refuse. Reading this as a denial would disable every control on a
31
- * switchboard running without authEnforcement. The code is what a client
32
- * branches on, since the message is not a contract.
33
- */
34
- var AuthEvaluationUnsupportedError = class extends GraphQLError {
35
- constructor() {
36
- super("Authorization evaluation is unavailable: this reactor runs without the authEnforcement feature flag, so it holds no decision model", { extensions: { code: "AUTH_EVALUATION_UNSUPPORTED" } });
37
- }
38
- };
39
- /**
40
- * A stored operation cannot be represented in the schema, so it is reported
41
- * rather than served.
42
- *
43
- * The schema declares an action's id, type, timestamp, input and scope
44
- * non-null; an operation written before the API rejected an action without an
45
- * id violates that. Left to the executor, the missing value nullifies the
46
- * action, which bubbles up through the non-null chain until it nullifies the
47
- * envelope's whole operation list, and the caller receives a partial response
48
- * beside "Cannot return null for non-nullable field Action.id" - which says
49
- * nothing about which operation, and which a sync client can only read as a
50
- * permanent GraphQL rejection, stopping its poll timer for good.
51
- *
52
- * Thrown instead, with a code that says the failure is worth polling through:
53
- * the document holding the operation needs repairing, but the channel serves
54
- * every other document, and a peer that stopped polling would stop receiving
55
- * those too. The code is what a client branches on, since the message is not a
56
- * contract.
57
- */
58
- var MalformedStoredOperationError = class extends GraphQLError {
59
- constructor(detail) {
60
- super(`Stored operation cannot be served: ${detail}`, { extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation } });
61
- }
62
- };
63
- //#endregion
64
- //#region src/services/authorization.service.ts
65
- /**
66
- * Result of a passed per-document authorization check. `fetchIdentifier` is
67
- * always safe for the data fetch: the canonical id when resolved, or the raw
68
- * identifier when the check was skipped for a policy-wide caller.
69
- */
70
- var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
71
- constructor(fetchIdentifier, isResolved) {
72
- this.fetchIdentifier = fetchIdentifier;
73
- this.isResolved = isResolved;
74
- }
75
- static resolved(documentId) {
76
- return new AuthorizedDocumentHandle(documentId, true);
77
- }
78
- static skipped(identifier) {
79
- return new AuthorizedDocumentHandle(identifier, false);
80
- }
81
- /** The verified canonical id; throws when resolution was skipped. */
82
- canonicalId() {
83
- if (!this.isResolved) throw new Error("Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller");
84
- return this.fetchIdentifier;
85
- }
86
- };
87
- const AuthorizationPolicy = {
88
- OPEN: "OPEN",
89
- ADMIN_ONLY: "ADMIN_ONLY",
90
- DOCUMENT_PERMISSIONS: "DOCUMENT_PERMISSIONS"
91
- };
92
- /** Shared config holder and admin-list check for the policy strategies. */
93
- var BaseAuthorizationService = class {
94
- constructor(config) {
95
- this.config = config;
96
- }
97
- isSupremeAdmin(userAddress) {
98
- if (!userAddress) return false;
99
- return this.config.admins.includes(userAddress.toLowerCase());
100
- }
101
- };
102
- /** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */
103
- var OpenAuthorizationService = class extends BaseAuthorizationService {
104
- isSupremeAdmin() {
105
- return true;
106
- }
107
- canCreate() {
108
- return true;
109
- }
110
- canRead() {
111
- return Promise.resolve(true);
112
- }
113
- canWrite() {
114
- return Promise.resolve(true);
115
- }
116
- canManage() {
117
- return Promise.resolve(true);
118
- }
119
- canMutate() {
120
- return Promise.resolve(true);
121
- }
122
- };
123
- /** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */
124
- var AdminOnlyAuthorizationService = class extends BaseAuthorizationService {
125
- canCreate(userAddress) {
126
- return this.isSupremeAdmin(userAddress);
127
- }
128
- canRead(_documentId, userAddress) {
129
- return Promise.resolve(this.isSupremeAdmin(userAddress));
130
- }
131
- canWrite(_documentId, userAddress) {
132
- return Promise.resolve(this.isSupremeAdmin(userAddress));
133
- }
134
- canManage(_documentId, userAddress) {
135
- return Promise.resolve(this.isSupremeAdmin(userAddress));
136
- }
137
- canMutate(_documentId, _operationType, userAddress) {
138
- return Promise.resolve(this.isSupremeAdmin(userAddress));
139
- }
140
- };
141
- const PERMISSION_RANK = {
142
- READ: 1,
143
- WRITE: 2,
144
- ADMIN: 3
145
- };
146
- function satisfies(level, required) {
147
- return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];
148
- }
149
- /**
150
- * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.
151
- *
152
- * All decisions live here; DocumentPermissionService is the data-access
153
- * layer underneath (grants, protection rows, owners).
154
- */
155
- var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationService {
156
- #permissions;
157
- #getParentIds;
158
- constructor(permissions, getParentIds, config) {
159
- super(config);
160
- this.#permissions = permissions;
161
- this.#getParentIds = getParentIds;
162
- }
163
- canCreate(userAddress) {
164
- return this.isSupremeAdmin(userAddress) || !!userAddress;
165
- }
166
- canRead(documentId, userAddress) {
167
- return this.#canAccess(documentId, "READ", userAddress);
168
- }
169
- canWrite(documentId, userAddress) {
170
- return this.#canAccess(documentId, "WRITE", userAddress);
171
- }
172
- canManage(documentId, userAddress) {
173
- return this.#isDocumentAdmin(documentId, userAddress);
174
- }
175
- async canMutate(documentId, operationType, userAddress) {
176
- if (this.isSupremeAdmin(userAddress)) return true;
177
- if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
178
- if (!userAddress) return false;
179
- if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
180
- return this.#permissions.hasOperationGrant(documentId, operationType, userAddress);
181
- }
182
- return this.#canAccess(documentId, "WRITE", userAddress);
183
- }
184
- /**
185
- * The one "administers this document" predicate: supreme admin, document
186
- * owner, or ADMIN grant on the document itself.
187
- */
188
- async #isDocumentAdmin(documentId, userAddress) {
189
- if (this.isSupremeAdmin(userAddress)) return true;
190
- if (!userAddress) return false;
191
- const owner = await this.#permissions.getDocumentOwner(documentId);
192
- if (owner && owner === userAddress.toLowerCase()) return true;
193
- return satisfies(await this.#grantLevel(documentId, userAddress), "ADMIN");
194
- }
195
- /**
196
- * The one read/write decision shape: supreme admin → unprotected (self or
197
- * ancestor) → owner → inherited grant of at least the required level.
198
- */
199
- async #canAccess(documentId, required, userAddress) {
200
- if (this.isSupremeAdmin(userAddress)) return true;
201
- if (!await this.#permissions.isProtectedWithAncestors(documentId, this.#getParentIds)) return true;
202
- if (!userAddress) return false;
203
- const owner = await this.#permissions.getDocumentOwner(documentId);
204
- if (owner && owner === userAddress.toLowerCase()) return true;
205
- return this.#hasGrantInHierarchy(documentId, userAddress, required);
206
- }
207
- /** Best grant the user holds on the document. */
208
- async #grantLevel(documentId, userAddress) {
209
- return this.#permissions.getUserPermission(documentId, userAddress);
210
- }
211
- /**
212
- * Walks the parent hierarchy (with cycle protection) looking for a grant of
213
- * at least the required level on the document or any ancestor.
214
- */
215
- async #hasGrantInHierarchy(documentId, userAddress, required) {
216
- const visited = /* @__PURE__ */ new Set();
217
- const queue = [documentId];
218
- while (queue.length > 0) {
219
- const current = queue.shift();
220
- if (visited.has(current)) continue;
221
- visited.add(current);
222
- if (satisfies(await this.#grantLevel(current, userAddress), required)) return true;
223
- for (const parentId of await this.#getParentIds(current)) if (!visited.has(parentId)) queue.push(parentId);
224
- }
225
- return false;
226
- }
227
- };
228
- /**
229
- * Selects the strategy for the configured policy. The strategy classes are
230
- * not exported, so this guard is the only construction path.
231
- */
232
- function createAuthorizationService(config, documentPermissionService, getParentIds) {
233
- if (config.policy === AuthorizationPolicy.OPEN) return new OpenAuthorizationService(config);
234
- if (config.policy === AuthorizationPolicy.ADMIN_ONLY) return new AdminOnlyAuthorizationService(config);
235
- if (!documentPermissionService) throw new Error("DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy");
236
- if (!getParentIds) throw new Error("A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy");
237
- return new DocumentPermissionsAuthorizationService(documentPermissionService, getParentIds, config);
238
- }
239
- //#endregion
240
- //#region src/services/canonical-document-id.ts
241
- /**
242
- * Raised when a caller-supplied identifier cannot be resolved to a canonical
243
- * document id. Carries no detail on purpose: resolution failures must not act
244
- * as a document-existence oracle, so consumers map this to their generic
245
- * fail-closed response.
246
- */
247
- var CanonicalDocumentIdResolutionError = class extends Error {
248
- constructor() {
249
- super("Document identifier could not be resolved");
250
- this.name = "CanonicalDocumentIdResolutionError";
251
- }
252
- };
253
- /**
254
- * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer
255
- * and server routes must resolve caller identifiers through this helper so
256
- * decision and data layers always agree on the subject document.
257
- */
258
- function createCanonicalDocumentIdResolver(client) {
259
- return async (identifier) => {
260
- let resolved;
261
- try {
262
- resolved = await client.resolveIdOrSlug(identifier);
263
- } catch {
264
- throw new CanonicalDocumentIdResolutionError();
265
- }
266
- return resolved;
267
- };
268
- }
269
- //#endregion
270
- //#region src/graphql/base-subgraph.ts
271
- var BaseSubgraph = class {
272
- name = "example";
273
- path = "";
274
- resolvers = { Query: { hello: () => this.name } };
275
- typeDefs = gql`
276
- type Query {
277
- hello: String
278
- }
279
- `;
280
- reactorClient;
281
- /** This package's namespaced slice of the HTTP surface. */
282
- http;
283
- graphqlManager;
284
- relationalDb;
285
- syncManager;
286
- documentPermissionService;
287
- authorizationService;
288
- syncServingGate;
289
- /**
290
- * Per-request memo of raw identifier to canonical document id, keyed on the
291
- * request context object so entries are released when the request ends. Lets
292
- * batch resolvers resolve each distinct identifier at most once.
293
- */
294
- #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
295
- #resolveCanonical;
296
- constructor(args) {
297
- this.#resolveCanonical = createCanonicalDocumentIdResolver(args.reactorClient);
298
- this.http = args.http;
299
- this.reactorClient = args.reactorClient;
300
- this.graphqlManager = args.graphqlManager;
301
- this.relationalDb = args.relationalDb;
302
- this.syncManager = args.syncManager;
303
- this.documentPermissionService = args.documentPermissionService;
304
- this.authorizationService = args.authorizationService;
305
- this.syncServingGate = args.syncServingGate;
306
- this.path = args.path ?? "";
307
- }
308
- async onSetup() {}
309
- async onDisconnect() {}
310
- /**
311
- * Resolves a caller-supplied identifier (id or slug) to its canonical
312
- * document id, memoized per request. Both the decision layer and the data
313
- * layer must agree on the subject, so this runs the same resolveIdOrSlug
314
- * lookup the data path uses. A resolution failure (not found, ambiguous, or
315
- * transient) surfaces as a generic Forbidden, fail-closed, so a bad
316
- * identifier cannot be used as a document-existence oracle.
317
- */
318
- async resolveCanonicalDocumentId(identifier, requestKey) {
319
- let cache = this.#canonicalIdMemo.get(requestKey);
320
- if (!cache) {
321
- cache = /* @__PURE__ */ new Map();
322
- this.#canonicalIdMemo.set(requestKey, cache);
323
- }
324
- const cached = cache.get(identifier);
325
- if (cached !== void 0) return cached;
326
- let canonical;
327
- try {
328
- canonical = await this.#resolveCanonical(identifier);
329
- } catch {
330
- throw new ForbiddenError();
331
- }
332
- cache.set(identifier, canonical);
333
- return canonical;
334
- }
335
- /**
336
- * Resolves the args' `documentId` to canonical form. Unconditional (unlike the
337
- * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.
338
- */
339
- async withCanonicalDocumentId(args, requestKey) {
340
- const documentId = await this.resolveCanonicalDocumentId(args.documentId, requestKey);
341
- return {
342
- ...args,
343
- documentId
344
- };
345
- }
346
- /**
347
- * Resolves an identifier for a per-document check, or null when the caller has
348
- * policy-wide access (OPEN or supreme admin) and the check can be skipped.
349
- * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail
350
- * closed without resolving.
351
- */
352
- async #resolveForCheck(identifier, ctx) {
353
- if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return null;
354
- if (this.authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
355
- return this.resolveCanonicalDocumentId(identifier, ctx);
356
- }
357
- /**
358
- * Read filter for an already-canonical document id (one sourced from the data
359
- * layer, such as a fetched document's id). Performs no slug resolution.
360
- */
361
- async canReadDocument(documentId, ctx) {
362
- return this.authorizationService.canRead(documentId, ctx.user?.address);
363
- }
364
- /**
365
- * The principal a request decides as: the authenticated caller's address, and
366
- * the did:key of the app instance whose token authenticated it.
367
- *
368
- * Both, because a policy can name either. The key is what a document records
369
- * as its creator, so a subject built without one cannot match the creator's
370
- * standing permission over the auth scope -- the document's own creator would
371
- * be refused an operation the write path accepts, since a signed action
372
- * carries the same key. Anonymous callers supply neither.
373
- */
374
- viewSubject(ctx) {
375
- return {
376
- address: ctx.user?.address,
377
- key: ctx.user?.appKey
378
- };
379
- }
380
- /**
381
- * Asserts read access, resolving a slug first. Returns a handle whose
382
- * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.
383
- */
384
- async assertCanRead(identifier, ctx) {
385
- const documentId = await this.#resolveForCheck(identifier, ctx);
386
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
387
- await this.assertCanReadCanonical(documentId, ctx);
388
- return AuthorizedDocumentHandle.resolved(documentId);
389
- }
390
- async assertCanWrite(identifier, ctx) {
391
- const documentId = await this.#resolveForCheck(identifier, ctx);
392
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
393
- await this.assertCanWriteCanonical(documentId, ctx);
394
- return AuthorizedDocumentHandle.resolved(documentId);
395
- }
396
- async assertCanExecuteOperation(identifier, operationType, ctx) {
397
- const documentId = await this.#resolveForCheck(identifier, ctx);
398
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
399
- await this.assertCanExecuteOperationCanonical(documentId, operationType, ctx);
400
- return AuthorizedDocumentHandle.resolved(documentId);
401
- }
402
- /**
403
- * Read assertion for an already-canonical document id. No slug resolution;
404
- * use only with ids sourced from the data layer or already resolved.
405
- */
406
- async assertCanReadCanonical(documentId, ctx) {
407
- if (!await this.authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
408
- }
409
- async assertCanWriteCanonical(documentId, ctx) {
410
- if (!await this.authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write to this document");
411
- }
412
- async assertCanExecuteOperationCanonical(documentId, operationType, ctx) {
413
- if (!await this.authorizationService.canMutate(documentId, operationType, ctx.user?.address)) throw new ForbiddenError(`to execute operation "${operationType}" on this document`);
414
- }
415
- assertCanCreate(ctx) {
416
- if (this.authorizationService.canCreate(ctx.user?.address)) return;
417
- if (ctx.user?.address) throw new ForbiddenError("to create documents");
418
- throw new AuthenticationRequiredError("to create documents");
419
- }
420
- };
421
- //#endregion
422
- //#region src/packages/import-resolver.ts
423
- /**
424
- * Imports a specifier that may be either a bare package specifier or a
425
- * filesystem path. Absolute paths are converted to file:// URLs, because the
426
- * ESM loader reads the drive letter in a Windows path as a URL scheme
427
- * (`import('D:\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).
428
- */
429
- async function importSpecifier(target) {
430
- return await (path.isAbsolute(target) ? import(pathToFileURL(target).href) : import(target));
431
- }
432
- /**
433
- * Attempts to import from suggested Node.js paths
434
- */
435
- async function tryNodeSuggestedPaths(packageName, subPath) {
436
- const suggestedPaths = [
437
- `${packageName}/dist/node/${subPath}/index.mjs`,
438
- `${packageName}/dist/node/${subPath}.mjs`,
439
- `${packageName}/dist/${subPath}/index.js`,
440
- `${packageName}/dist/${subPath}.js`
441
- ];
442
- for (const suggestedPath of suggestedPaths) try {
443
- return await importSpecifier(suggestedPath);
444
- } catch {}
445
- return null;
446
- }
447
- /**
448
- * Attempts to resolve package using import.meta.resolve
449
- */
450
- async function tryImportMetaResolve(packageName, subPath) {
451
- try {
452
- const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
453
- if (!resolvedUrl) return null;
454
- const packageRoot = path.dirname(fileURLToPath(resolvedUrl));
455
- const pathsToTry = [
456
- path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
457
- path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
458
- path.join(packageRoot, "dist", subPath, "index.js"),
459
- path.join(packageRoot, "dist", `${subPath}.js`),
460
- path.join(packageRoot, subPath, "index.js"),
461
- path.join(packageRoot, `${subPath}.js`)
462
- ];
463
- for (const attemptPath of pathsToTry) try {
464
- return await importSpecifier(attemptPath);
465
- } catch {}
466
- } catch {}
467
- return null;
468
- }
469
- /**
470
- * Resolves symlinks in node_modules to find the real package location
471
- */
472
- async function resolveSymlinkedPaths(packageName, subPath) {
473
- const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
474
- const nodeModulesPatterns = [path.join(process.cwd(), "node_modules", packageName), path.join(process.cwd(), "node_modules", packageBaseName || packageName)];
475
- const workspacePatterns = [];
476
- for (const nodeModulesPath of nodeModulesPatterns) try {
477
- const fs = await import("node:fs");
478
- if (fs.existsSync(nodeModulesPath)) {
479
- const realPath = fs.realpathSync(nodeModulesPath);
480
- workspacePatterns.push(path.join(realPath, "dist", "node", subPath, "index.mjs"), path.join(realPath, "dist", "node", `${subPath}.mjs`), path.join(realPath, "dist", subPath, "index.js"), path.join(realPath, "dist", `${subPath}.js`), path.join(realPath, subPath, "index.js"), path.join(realPath, `${subPath}.js`));
481
- }
482
- } catch {}
483
- return workspacePatterns;
484
- }
485
- /**
486
- * Generates common workspace pattern paths
487
- */
488
- function getCommonWorkspacePaths(packageName, subPath) {
489
- const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
490
- const commonRoots = [process.cwd(), path.dirname(process.cwd())];
491
- const workspacePatterns = [];
492
- for (const root of commonRoots) workspacePatterns.push(path.join(root, "packages", packageBaseName || packageName, "dist", "node", subPath, "index.mjs"), path.join(root, "packages", packageBaseName || packageName, "dist", "node", `${subPath}.mjs`), path.join(root, "packages", packageBaseName || packageName, "dist", subPath, "index.js"), path.join(root, "packages", packageBaseName || packageName, "dist", `${subPath}.js`));
493
- return workspacePatterns;
494
- }
495
- /**
496
- * Attempts to import from a list of workspace patterns
497
- */
498
- async function tryWorkspacePatterns(patterns) {
499
- for (const workspacePath of patterns) try {
500
- return await importSpecifier(workspacePath);
501
- } catch {}
502
- return null;
503
- }
504
- /**
505
- * Attempts to resolve linked packages using various fallback strategies
506
- */
507
- async function resolveLinkedPackage(packageName, subPath) {
508
- let result = await tryNodeSuggestedPaths(packageName, subPath);
509
- if (result) return result;
510
- result = await tryImportMetaResolve(packageName, subPath);
511
- if (result) return result;
512
- result = await tryWorkspacePatterns(await resolveSymlinkedPaths(packageName, subPath));
513
- if (result) return result;
514
- result = await tryWorkspacePatterns(getCommonWorkspacePaths(packageName, subPath));
515
- if (result) return result;
516
- return null;
517
- }
518
- //#endregion
519
- //#region src/packages/util.ts
520
- childLogger(["reactor-api", "packages/util"]);
521
- /**
522
- * Tries to import document models from a package. This function cannot throw.
523
- */
524
- async function loadDocumentModels(packageName) {
525
- return loadDependency(packageName, "document-models");
526
- }
527
- /**
528
- * Tries to import subgraphs from a package. This function cannot throw.
529
- */
530
- async function loadSubgraphs(packageName) {
531
- return loadDependency(packageName, "subgraphs");
532
- }
533
- /**
534
- * Tries to import processors from a package. This function cannot throw.
535
- */
536
- async function loadProcessors(packageName) {
537
- return loadDependency(packageName, "processors");
538
- }
539
- /**
540
- * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.
541
- * Returns null if the dependency cannot be loaded.
542
- */
543
- async function loadDependency(packageName, subPath) {
544
- const fullPath = path.isAbsolute(packageName) ? pathToFileURL(path.join(packageName, subPath)).href : `${packageName}/${subPath}`;
545
- try {
546
- return await import(
547
- /* @vite-ignore */
548
- fullPath
549
- );
550
- } catch (e) {
551
- if (e instanceof Error && "code" in e && (e.code === "ERR_MODULE_NOT_FOUND" || e.code === "ERR_UNSUPPORTED_DIR_IMPORT" || e.code === "ERR_UNSUPPORTED_ESM_URL_SCHEME")) {
552
- const result = await resolveLinkedPackage(packageName, subPath);
553
- if (result) return result;
554
- }
555
- throw e;
556
- }
557
- }
558
- function isUpgradeManifest(value) {
559
- return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
560
- }
561
- /**
562
- * Collects upgrade manifests from a package's document-models namespace.
563
- * Handles both the aggregate `upgradeManifests` array export and individual
564
- * manifest exports; dedupes by documentType.
565
- */
566
- function extractUpgradeManifests(namespace) {
567
- const manifests = /* @__PURE__ */ new Map();
568
- const add = (value) => {
569
- if (isUpgradeManifest(value)) manifests.set(value.documentType, value);
570
- };
571
- for (const value of Object.values(namespace)) if (Array.isArray(value)) value.forEach(add);
572
- else add(value);
573
- return Array.from(manifests.values());
574
- }
575
- function debounce(func, delay = 250) {
576
- let timer;
577
- return (immediate = false, ...args) => {
578
- if (timer) clearTimeout(timer);
579
- return new Promise((resolve, reject) => {
580
- if (immediate) func(...args).then(resolve).catch(reject);
581
- else timer = setTimeout(() => {
582
- func(...args).then(resolve).catch(reject);
583
- }, delay);
584
- });
585
- };
586
- }
587
- function isSubpath(parent, dir) {
588
- const relative = path.relative(parent, dir);
589
- return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
590
- }
591
- //#endregion
592
- //#region src/graphql/utils.ts
593
- function isSubgraphClass(candidate) {
594
- if (typeof candidate !== "function") return false;
595
- let proto = Object.getPrototypeOf(candidate);
596
- while (proto) {
597
- if (Object.prototype.isPrototypeOf.call(proto, BaseSubgraph)) return true;
598
- proto = Object.getPrototypeOf(proto);
599
- }
600
- return false;
601
- }
602
- function buildGraphqlOperations(operations, skip, first) {
603
- return operations.slice(skip, skip + first).map(buildGraphqlOperation);
604
- }
605
- function buildGraphqlOperation(operation) {
606
- const signer = operation.action.context?.signer;
607
- return {
608
- id: operation.id ?? "",
609
- type: operation.action.type,
610
- index: operation.index,
611
- timestampUtcMs: operation.timestampUtcMs,
612
- hash: operation.hash,
613
- skip: operation.skip,
614
- inputText: typeof operation.action.input === "string" ? operation.action.input : JSON.stringify(operation.action.input),
615
- error: operation.error,
616
- context: { signer: signer ? {
617
- user: signer.user,
618
- app: signer.app,
619
- signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
620
- } : void 0 }
621
- };
622
- }
623
- function buildGraphQlDocument(doc) {
624
- const state = doc.state;
625
- const initialState = doc.initialState;
626
- const globalState = "global" in doc.state ? doc.state.global : {};
627
- return {
628
- id: doc.header.id,
629
- name: doc.header.name,
630
- documentType: doc.header.documentType,
631
- revision: doc.header.revision.global || 0,
632
- createdAtUtcIso: doc.header.createdAtUtcIso,
633
- lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,
634
- operations: [],
635
- stateJSON: globalState,
636
- state,
637
- initialState
638
- };
639
- }
640
- function buildGraphQlDriveDocument(doc) {
641
- return {
642
- ...buildGraphQlDocument(doc),
643
- meta: { preferredEditor: doc.header.meta?.preferredEditor },
644
- slug: doc.header.slug,
645
- state: doc.state.global,
646
- initialState: doc.state.global
647
- };
648
- }
649
- //#endregion
650
- export { createAuthorizationService as _, isSubgraphClass as a, MalformedStoredOperationError as b, isSubpath as c, loadSubgraphs as d, BaseSubgraph as f, AuthorizedDocumentHandle as g, AuthorizationPolicy as h, buildGraphqlOperations as i, loadDocumentModels as l, createCanonicalDocumentIdResolver as m, buildGraphQlDriveDocument as n, debounce as o, CanonicalDocumentIdResolutionError as p, buildGraphqlOperation as r, extractUpgradeManifests as s, buildGraphQlDocument as t, loadProcessors as u, AuthEvaluationUnsupportedError as v, ForbiddenError as y };
651
-
652
- //# sourceMappingURL=utils-XWVecaNn.mjs.map
653
- //# debugId=df700b05-17ec-5ac9-b31f-f6f9cfcfa5f5