@powerhousedao/reactor-api 6.2.0-dev.2 → 6.2.0-dev.20

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,6 +1,6 @@
1
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]="1ea545f7-1fd6-5398-9906-11c687b497c5")}catch(e){}}();
3
- import { a as isSubgraphClass, o as debounce, s as isSubpath } from "../../utils-BFkbSO_H.mjs";
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]="02fc7276-e4d6-5195-b4ce-5791df961225")}catch(e){}}();
3
+ import { a as isSubgraphClass, o as debounce, s as isSubpath } from "../../utils-Dh9tl892.mjs";
4
4
  import { childLogger } from "document-model";
5
5
  import path from "node:path";
6
6
  import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
@@ -142,4 +142,4 @@ async function startViteServer(root, logger) {
142
142
  export { VitePackageLoader, createViteLogger, startViteServer };
143
143
 
144
144
  //# sourceMappingURL=vite-loader.mjs.map
145
- //# debugId=1ea545f7-1fd6-5398-9906-11c687b497c5
145
+ //# debugId=02fc7276-e4d6-5195-b4ce-5791df961225
@@ -1 +1 @@
1
- {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { isSubgraphClass } from \"../graphql/utils.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n} from \"./types.js\";\nimport { debounce, isSubpath } from \"./util.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n customLogger.info = logger.info;\n customLogger.warn = logger.warn;\n customLogger.error = logger.error;\n return customLogger;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer) {\n return new VitePackageLoader(vite);\n }\n\n constructor(vite: ViteDevServer) {\n this.vite = vite;\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.join(identifier, \"./processors\");\n }\n\n public loadDocumentModels(identifier: string, immediate = false) {\n return this.#loadDocumentModelsWithDebounce(immediate, identifier);\n }\n\n #loadDocumentModelsWithDebounce = debounce(\n this.#loadDocumentModels.bind(this),\n 500,\n );\n\n async #loadDocumentModels(\n identifier: string,\n ): Promise<DocumentModelModule[]> {\n const fullPath = this.getDocumentModelsPath(identifier);\n this.logger.debug(\"Loading document models from\", fullPath);\n\n try {\n const localDMs = (await this.vite.ssrLoadModule(fullPath)) as Record<\n string,\n DocumentModelModule\n >;\n\n const exports = Object.values(localDMs);\n\n // duck type\n const documentModels: DocumentModelModule[] = [];\n for (const dm of exports) {\n if (dm.documentModel) {\n documentModels.push(dm);\n }\n }\n\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n\n return documentModels;\n } catch (e) {\n this.logger.debug(` ➜ No Document Models found for: ${identifier}`, e);\n }\n\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n const fullPath = this.getSubgraphsPath(identifier);\n\n this.logger.verbose(\"Loading subgraphs from\", fullPath);\n\n let localSubgraphs: Record<string, Record<string, SubgraphClass>> = {};\n try {\n localSubgraphs = await this.vite.ssrLoadModule(fullPath);\n } catch (e) {\n this.logger.debug(` ➜ No Subgraphs found for: ${identifier}`, e);\n return [];\n }\n\n const subgraphs: SubgraphClass[] = [];\n for (const [name, subgraph] of Object.entries(localSubgraphs)) {\n const SubgraphClass = subgraph[name];\n if (isSubgraphClass(SubgraphClass)) {\n subgraphs.push(SubgraphClass);\n }\n }\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n const fullPath = this.getProcessorsPath(identifier);\n\n this.logger.verbose(\"Loading processors from\", fullPath);\n\n try {\n const pkgModule = await this.vite.ssrLoadModule(fullPath);\n\n const factory = (\n pkgModule as Record<string, ProcessorFactoryBuilder | undefined>\n )?.processorFactory;\n\n if (factory && typeof factory === \"function\") {\n this.logger.verbose(\n ` ➜ Loaded Processor Factory from: ${identifier}`,\n );\n return factory;\n }\n } catch (e) {\n this.logger.debug(\n ` ➜ No Processor Factory found for: ${identifier}`,\n e,\n );\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n\n // return empty processor factory\n return null;\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const listener = async (changedPath: string) => {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n if (isSubpath(documentModelsPath, changedPath)) {\n const documentModels = await this.loadDocumentModels(identifier);\n handler(documentModels);\n }\n };\n\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n const listener = debounce(async (changedPath: string) => {\n if (isSubpath(subgraphsPath, changedPath)) {\n const subgraphs = await this.loadSubgraphs(identifier);\n handler(subgraphs);\n }\n }, options?.debounce ?? 100);\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n const listener = async (changedPath: string) => {\n if (isSubpath(processorsPath, changedPath)) {\n const processors = await this.loadProcessors(identifier);\n handler(processors);\n }\n };\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: { middlewareMode: true, watch: { ignored: [\"**/.ph/**\"] } },\n appType: \"custom\",\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n viteCommonjs(),\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":["#loadDocumentModelsWithDebounce","#loadDocumentModels"],"mappings":";;;;;;;;;AAkBA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,QACD,CAAC;AACF,cAAa,OAAO,OAAO;AAC3B,cAAa,OAAO,OAAO;AAC3B,cAAa,QAAQ,OAAO;AAC5B,QAAO;;AAGT,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,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MAAM,KAAK,eAAe,WAAW,CACrC;;AAGvB,OAAK,KAAK,QAAQ,GAAG,UAAU,SAAS;AAExC,eAAa;AACX,QAAK,KAAK,QAAQ,IAAI,UAAU,SAAS;;;;AAK/C,eAAsB,gBAAgB,MAAc,QAAiB;AA+BnE,QA5Ba,MAAM,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GAAE,gBAAgB;GAAM,OAAO,EAAE,SAAS,CAAC,YAAY,EAAE;GAAE;EACnE,SAAS;EACT,OAAO,EACL,eAAe,EACb,OAAO,EAAE,EACV,EACF;EACD,SAAS;GACP,eAAe;GACf,OAAO,IAfS,MAAM,YAAY,EAAE,KAAK,MAAM,CAAC,EAgBjC,OAAO,MACrB;GACF;EACD,SAAS,CACP,cAAc,EACd;GACE,MAAM;GACN,kBAAkB;AAChB,WAAO,EAAE;;GAEZ,CACF;EACF,CAAC","debug_id":"1ea545f7-1fd6-5398-9906-11c687b497c5"}
1
+ {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { isSubgraphClass } from \"../graphql/utils.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n} from \"./types.js\";\nimport { debounce, isSubpath } from \"./util.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n customLogger.info = logger.info;\n customLogger.warn = logger.warn;\n customLogger.error = logger.error;\n return customLogger;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer) {\n return new VitePackageLoader(vite);\n }\n\n constructor(vite: ViteDevServer) {\n this.vite = vite;\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.join(identifier, \"./processors\");\n }\n\n public loadDocumentModels(identifier: string, immediate = false) {\n return this.#loadDocumentModelsWithDebounce(immediate, identifier);\n }\n\n #loadDocumentModelsWithDebounce = debounce(\n this.#loadDocumentModels.bind(this),\n 500,\n );\n\n async #loadDocumentModels(\n identifier: string,\n ): Promise<DocumentModelModule[]> {\n const fullPath = this.getDocumentModelsPath(identifier);\n this.logger.debug(\"Loading document models from\", fullPath);\n\n try {\n const localDMs = (await this.vite.ssrLoadModule(fullPath)) as Record<\n string,\n DocumentModelModule\n >;\n\n const exports = Object.values(localDMs);\n\n // duck type\n const documentModels: DocumentModelModule[] = [];\n for (const dm of exports) {\n if (dm.documentModel) {\n documentModels.push(dm);\n }\n }\n\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n\n return documentModels;\n } catch (e) {\n this.logger.debug(` ➜ No Document Models found for: ${identifier}`, e);\n }\n\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n const fullPath = this.getSubgraphsPath(identifier);\n\n this.logger.verbose(\"Loading subgraphs from\", fullPath);\n\n let localSubgraphs: Record<string, Record<string, SubgraphClass>> = {};\n try {\n localSubgraphs = await this.vite.ssrLoadModule(fullPath);\n } catch (e) {\n this.logger.debug(` ➜ No Subgraphs found for: ${identifier}`, e);\n return [];\n }\n\n const subgraphs: SubgraphClass[] = [];\n for (const [name, subgraph] of Object.entries(localSubgraphs)) {\n const SubgraphClass = subgraph[name];\n if (isSubgraphClass(SubgraphClass)) {\n subgraphs.push(SubgraphClass);\n }\n }\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n const fullPath = this.getProcessorsPath(identifier);\n\n this.logger.verbose(\"Loading processors from\", fullPath);\n\n try {\n const pkgModule = await this.vite.ssrLoadModule(fullPath);\n\n const factory = (\n pkgModule as Record<string, ProcessorFactoryBuilder | undefined>\n )?.processorFactory;\n\n if (factory && typeof factory === \"function\") {\n this.logger.verbose(\n ` ➜ Loaded Processor Factory from: ${identifier}`,\n );\n return factory;\n }\n } catch (e) {\n this.logger.debug(\n ` ➜ No Processor Factory found for: ${identifier}`,\n e,\n );\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n\n // return empty processor factory\n return null;\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const listener = async (changedPath: string) => {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n if (isSubpath(documentModelsPath, changedPath)) {\n const documentModels = await this.loadDocumentModels(identifier);\n handler(documentModels);\n }\n };\n\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n const listener = debounce(async (changedPath: string) => {\n if (isSubpath(subgraphsPath, changedPath)) {\n const subgraphs = await this.loadSubgraphs(identifier);\n handler(subgraphs);\n }\n }, options?.debounce ?? 100);\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n const listener = async (changedPath: string) => {\n if (isSubpath(processorsPath, changedPath)) {\n const processors = await this.loadProcessors(identifier);\n handler(processors);\n }\n };\n this.vite.watcher.on(\"change\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n };\n }\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: { middlewareMode: true, watch: { ignored: [\"**/.ph/**\"] } },\n appType: \"custom\",\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":["#loadDocumentModelsWithDebounce","#loadDocumentModels"],"mappings":";;;;;;;;;AAkBA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,QACD,CAAC;AACF,cAAa,OAAO,OAAO;AAC3B,cAAa,OAAO,OAAO;AAC3B,cAAa,QAAQ,OAAO;AAC5B,QAAO;;AAGT,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,eAAe,cAAc,CAAC;CAErE;CAEA,OAAgB;CAEhB,OAAO,MAAM,MAAqB;AAChC,SAAO,IAAI,kBAAkB,KAAK;;CAGpC,YAAY,MAAqB;AAC/B,OAAK,OAAO;;CAGd,sBAA8B,YAA4B;AACxD,SAAO,KAAK,KAAK,YAAY,oBAAoB;;CAGnD,iBAAyB,YAA4B;AACnD,SAAO,KAAK,KAAK,YAAY,cAAc;;CAG7C,kBAA0B,YAA4B;AACpD,SAAO,KAAK,KAA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AAS;EACT,OAAO,EACL,eAAe,EACb,OAAO,EAAE,EACV,EACF;EACD,SAAS;GACP,eAAe;GACf,OAAO,IAfS,MAAM,YAAY,EAAE,KAAK,MAAM,CAAC,EAgBjC,OAAO,MACrB;GACF;EACD,SAAS,CAGP,cAAc,EACd;GACE,MAAM;GACN,kBAAkB;AAChB,WAAO,EAAE;;GAEZ,CACF;EACF,CAAC","debug_id":"02fc7276-e4d6-5195-b4ce-5791df961225"}
@@ -0,0 +1,530 @@
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]="02ee5aff-26c7-5e45-b81e-6ec7bce7f7ec")}catch(e){}}();
3
+ import { gql } from "graphql-tag";
4
+ import { GraphQLError } from "graphql";
5
+ import { childLogger } from "document-model";
6
+ import path from "node:path";
7
+ //#region src/services/authorization.service.ts
8
+ /**
9
+ * Result of a passed per-document authorization check. `fetchIdentifier` is
10
+ * always safe for the data fetch: the canonical id when resolved, or the raw
11
+ * identifier when the check was skipped for a policy-wide caller.
12
+ */
13
+ var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
14
+ constructor(fetchIdentifier, isResolved) {
15
+ this.fetchIdentifier = fetchIdentifier;
16
+ this.isResolved = isResolved;
17
+ }
18
+ static resolved(documentId) {
19
+ return new AuthorizedDocumentHandle(documentId, true);
20
+ }
21
+ static skipped(identifier) {
22
+ return new AuthorizedDocumentHandle(identifier, false);
23
+ }
24
+ /** The verified canonical id; throws when resolution was skipped. */
25
+ canonicalId() {
26
+ if (!this.isResolved) throw new Error("Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller");
27
+ return this.fetchIdentifier;
28
+ }
29
+ };
30
+ const AuthorizationPolicy = {
31
+ OPEN: "OPEN",
32
+ ADMIN_ONLY: "ADMIN_ONLY",
33
+ DOCUMENT_PERMISSIONS: "DOCUMENT_PERMISSIONS"
34
+ };
35
+ /** Shared config holder and admin-list check for the policy strategies. */
36
+ var BaseAuthorizationService = class {
37
+ constructor(config) {
38
+ this.config = config;
39
+ }
40
+ isSupremeAdmin(userAddress) {
41
+ if (!userAddress) return false;
42
+ return this.config.admins.includes(userAddress.toLowerCase());
43
+ }
44
+ };
45
+ /** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */
46
+ var OpenAuthorizationService = class extends BaseAuthorizationService {
47
+ isSupremeAdmin() {
48
+ return true;
49
+ }
50
+ canCreate() {
51
+ return true;
52
+ }
53
+ canRead() {
54
+ return Promise.resolve(true);
55
+ }
56
+ canWrite() {
57
+ return Promise.resolve(true);
58
+ }
59
+ canManage() {
60
+ return Promise.resolve(true);
61
+ }
62
+ canMutate() {
63
+ return Promise.resolve(true);
64
+ }
65
+ };
66
+ /** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */
67
+ var AdminOnlyAuthorizationService = class extends BaseAuthorizationService {
68
+ canCreate(userAddress) {
69
+ return this.isSupremeAdmin(userAddress);
70
+ }
71
+ canRead(_documentId, userAddress) {
72
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
73
+ }
74
+ canWrite(_documentId, userAddress) {
75
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
76
+ }
77
+ canManage(_documentId, userAddress) {
78
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
79
+ }
80
+ canMutate(_documentId, _operationType, userAddress) {
81
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
82
+ }
83
+ };
84
+ const PERMISSION_RANK = {
85
+ READ: 1,
86
+ WRITE: 2,
87
+ ADMIN: 3
88
+ };
89
+ function satisfies(level, required) {
90
+ return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];
91
+ }
92
+ /**
93
+ * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.
94
+ *
95
+ * All decisions live here; DocumentPermissionService is the data-access
96
+ * layer underneath (grants, groups, protection rows, owners).
97
+ */
98
+ var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationService {
99
+ #permissions;
100
+ #getParentIds;
101
+ constructor(permissions, getParentIds, config) {
102
+ super(config);
103
+ this.#permissions = permissions;
104
+ this.#getParentIds = getParentIds;
105
+ }
106
+ canCreate(userAddress) {
107
+ return this.isSupremeAdmin(userAddress) || !!userAddress;
108
+ }
109
+ canRead(documentId, userAddress) {
110
+ return this.#canAccess(documentId, "READ", userAddress);
111
+ }
112
+ canWrite(documentId, userAddress) {
113
+ return this.#canAccess(documentId, "WRITE", userAddress);
114
+ }
115
+ canManage(documentId, userAddress) {
116
+ return this.#isDocumentAdmin(documentId, userAddress);
117
+ }
118
+ async canMutate(documentId, operationType, userAddress) {
119
+ if (this.isSupremeAdmin(userAddress)) return true;
120
+ if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
121
+ if (!userAddress) return false;
122
+ if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
123
+ return this.#permissions.hasOperationGrant(documentId, operationType, userAddress);
124
+ }
125
+ return this.#canAccess(documentId, "WRITE", userAddress);
126
+ }
127
+ /**
128
+ * The one "administers this document" predicate: supreme admin, document
129
+ * owner, or ADMIN grant (direct or via group) on the document itself.
130
+ */
131
+ async #isDocumentAdmin(documentId, userAddress) {
132
+ if (this.isSupremeAdmin(userAddress)) return true;
133
+ if (!userAddress) return false;
134
+ const owner = await this.#permissions.getDocumentOwner(documentId);
135
+ if (owner && owner === userAddress.toLowerCase()) return true;
136
+ return satisfies(await this.#grantLevel(documentId, userAddress), "ADMIN");
137
+ }
138
+ /**
139
+ * The one read/write decision shape: supreme admin → unprotected (self or
140
+ * ancestor) → owner → inherited grant of at least the required level.
141
+ */
142
+ async #canAccess(documentId, required, userAddress) {
143
+ if (this.isSupremeAdmin(userAddress)) return true;
144
+ if (!await this.#permissions.isProtectedWithAncestors(documentId, this.#getParentIds)) return true;
145
+ if (!userAddress) return false;
146
+ const owner = await this.#permissions.getDocumentOwner(documentId);
147
+ if (owner && owner === userAddress.toLowerCase()) return true;
148
+ return this.#hasGrantInHierarchy(documentId, userAddress, required);
149
+ }
150
+ /** Best grant the user holds on the document, direct or via group. */
151
+ async #grantLevel(documentId, userAddress) {
152
+ const direct = await this.#permissions.getUserPermission(documentId, userAddress);
153
+ if (direct === "ADMIN") return direct;
154
+ const group = await this.#permissions.getUserGroupPermission(documentId, userAddress);
155
+ if (group === null) return direct;
156
+ if (direct === null) return group;
157
+ return PERMISSION_RANK[direct] >= PERMISSION_RANK[group] ? direct : group;
158
+ }
159
+ /**
160
+ * Walks the parent hierarchy (with cycle protection) looking for a grant of
161
+ * at least the required level on the document or any ancestor.
162
+ */
163
+ async #hasGrantInHierarchy(documentId, userAddress, required) {
164
+ const visited = /* @__PURE__ */ new Set();
165
+ const queue = [documentId];
166
+ while (queue.length > 0) {
167
+ const current = queue.shift();
168
+ if (visited.has(current)) continue;
169
+ visited.add(current);
170
+ if (satisfies(await this.#grantLevel(current, userAddress), required)) return true;
171
+ for (const parentId of await this.#getParentIds(current)) if (!visited.has(parentId)) queue.push(parentId);
172
+ }
173
+ return false;
174
+ }
175
+ };
176
+ /**
177
+ * Selects the strategy for the configured policy. The strategy classes are
178
+ * not exported, so this guard is the only construction path.
179
+ */
180
+ function createAuthorizationService(config, documentPermissionService, getParentIds) {
181
+ if (config.policy === AuthorizationPolicy.OPEN) return new OpenAuthorizationService(config);
182
+ if (config.policy === AuthorizationPolicy.ADMIN_ONLY) return new AdminOnlyAuthorizationService(config);
183
+ if (!documentPermissionService) throw new Error("DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy");
184
+ if (!getParentIds) throw new Error("A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy");
185
+ return new DocumentPermissionsAuthorizationService(documentPermissionService, getParentIds, config);
186
+ }
187
+ //#endregion
188
+ //#region src/graphql/base-subgraph.ts
189
+ var BaseSubgraph = class {
190
+ name = "example";
191
+ path = "";
192
+ resolvers = { Query: { hello: () => this.name } };
193
+ typeDefs = gql`
194
+ type Query {
195
+ hello: String
196
+ }
197
+ `;
198
+ reactorClient;
199
+ graphqlManager;
200
+ relationalDb;
201
+ syncManager;
202
+ documentPermissionService;
203
+ authorizationService;
204
+ /**
205
+ * Per-request memo of raw identifier to canonical document id, keyed on the
206
+ * request context object so entries are released when the request ends. Lets
207
+ * batch resolvers resolve each distinct identifier at most once.
208
+ */
209
+ #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
210
+ constructor(args) {
211
+ this.reactorClient = args.reactorClient;
212
+ this.graphqlManager = args.graphqlManager;
213
+ this.relationalDb = args.relationalDb;
214
+ this.syncManager = args.syncManager;
215
+ this.documentPermissionService = args.documentPermissionService;
216
+ this.authorizationService = args.authorizationService;
217
+ this.path = args.path ?? "";
218
+ }
219
+ async onSetup() {}
220
+ /**
221
+ * Resolves a caller-supplied identifier (id or slug) to its canonical
222
+ * document id, memoized per request. Both the decision layer and the data
223
+ * layer must agree on the subject, so this runs the same resolveIdOrSlug
224
+ * lookup the data path uses. A resolution failure (not found, ambiguous, or
225
+ * transient) surfaces as a generic Forbidden, fail-closed, so a bad
226
+ * identifier cannot be used as a document-existence oracle.
227
+ */
228
+ async resolveCanonicalDocumentId(identifier, requestKey) {
229
+ let cache = this.#canonicalIdMemo.get(requestKey);
230
+ if (!cache) {
231
+ cache = /* @__PURE__ */ new Map();
232
+ this.#canonicalIdMemo.set(requestKey, cache);
233
+ }
234
+ const cached = cache.get(identifier);
235
+ if (cached !== void 0) return cached;
236
+ let resolved;
237
+ try {
238
+ resolved = await this.reactorClient.resolveIdOrSlug(identifier);
239
+ } catch {
240
+ throw new GraphQLError("Forbidden: insufficient permissions");
241
+ }
242
+ const canonical = resolved;
243
+ cache.set(identifier, canonical);
244
+ return canonical;
245
+ }
246
+ /**
247
+ * Resolves the args' `documentId` to canonical form. Unconditional (unlike the
248
+ * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.
249
+ */
250
+ async withCanonicalDocumentId(args, requestKey) {
251
+ const documentId = await this.resolveCanonicalDocumentId(args.documentId, requestKey);
252
+ return {
253
+ ...args,
254
+ documentId
255
+ };
256
+ }
257
+ /**
258
+ * Resolves an identifier for a per-document check, or null when the caller has
259
+ * policy-wide access (OPEN or supreme admin) and the check can be skipped.
260
+ * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail
261
+ * closed without resolving.
262
+ */
263
+ async #resolveForCheck(identifier, ctx) {
264
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return null;
265
+ if (this.authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new GraphQLError("Forbidden: insufficient permissions");
266
+ return this.resolveCanonicalDocumentId(identifier, ctx);
267
+ }
268
+ /**
269
+ * Read filter for an already-canonical document id (one sourced from the data
270
+ * layer, such as a fetched document's id). Performs no slug resolution.
271
+ */
272
+ async canReadDocument(documentId, ctx) {
273
+ return this.authorizationService.canRead(documentId, ctx.user?.address);
274
+ }
275
+ /**
276
+ * Asserts read access, resolving a slug first. Returns a handle whose
277
+ * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.
278
+ */
279
+ async assertCanRead(identifier, ctx) {
280
+ const documentId = await this.#resolveForCheck(identifier, ctx);
281
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
282
+ await this.assertCanReadCanonical(documentId, ctx);
283
+ return AuthorizedDocumentHandle.resolved(documentId);
284
+ }
285
+ async assertCanWrite(identifier, ctx) {
286
+ const documentId = await this.#resolveForCheck(identifier, ctx);
287
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
288
+ await this.assertCanWriteCanonical(documentId, ctx);
289
+ return AuthorizedDocumentHandle.resolved(documentId);
290
+ }
291
+ async assertCanExecuteOperation(identifier, operationType, ctx) {
292
+ const documentId = await this.#resolveForCheck(identifier, ctx);
293
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
294
+ await this.assertCanExecuteOperationCanonical(documentId, operationType, ctx);
295
+ return AuthorizedDocumentHandle.resolved(documentId);
296
+ }
297
+ /**
298
+ * Read assertion for an already-canonical document id. No slug resolution;
299
+ * use only with ids sourced from the data layer or already resolved.
300
+ */
301
+ async assertCanReadCanonical(documentId, ctx) {
302
+ if (!await this.authorizationService.canRead(documentId, ctx.user?.address)) throw new GraphQLError("Forbidden: insufficient permissions to read this document");
303
+ }
304
+ async assertCanWriteCanonical(documentId, ctx) {
305
+ if (!await this.authorizationService.canWrite(documentId, ctx.user?.address)) throw new GraphQLError("Forbidden: insufficient permissions to write to this document");
306
+ }
307
+ async assertCanExecuteOperationCanonical(documentId, operationType, ctx) {
308
+ if (!await this.authorizationService.canMutate(documentId, operationType, ctx.user?.address)) throw new GraphQLError(`Forbidden: insufficient permissions to execute operation "${operationType}" on this document`);
309
+ }
310
+ assertCanCreate(ctx) {
311
+ if (this.authorizationService.canCreate(ctx.user?.address)) return;
312
+ throw new GraphQLError(ctx.user?.address ? "Forbidden: insufficient permissions to create documents" : "Forbidden: authentication required to create documents");
313
+ }
314
+ };
315
+ //#endregion
316
+ //#region src/packages/import-resolver.ts
317
+ /**
318
+ * Attempts to import from suggested Node.js paths
319
+ */
320
+ async function tryNodeSuggestedPaths(packageName, subPath) {
321
+ const suggestedPaths = [
322
+ `${packageName}/dist/node/${subPath}/index.mjs`,
323
+ `${packageName}/dist/node/${subPath}.mjs`,
324
+ `${packageName}/dist/${subPath}/index.js`,
325
+ `${packageName}/dist/${subPath}.js`
326
+ ];
327
+ for (const suggestedPath of suggestedPaths) try {
328
+ return await import(
329
+ /* @vite-ignore */
330
+ suggestedPath
331
+ );
332
+ } catch {}
333
+ return null;
334
+ }
335
+ /**
336
+ * Attempts to resolve package using import.meta.resolve
337
+ */
338
+ async function tryImportMetaResolve(packageName, subPath) {
339
+ try {
340
+ const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
341
+ if (!resolvedUrl) return null;
342
+ const packageRoot = path.dirname(new URL(resolvedUrl).pathname);
343
+ const pathsToTry = [
344
+ path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
345
+ path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
346
+ path.join(packageRoot, "dist", subPath, "index.js"),
347
+ path.join(packageRoot, "dist", `${subPath}.js`),
348
+ path.join(packageRoot, subPath, "index.js"),
349
+ path.join(packageRoot, `${subPath}.js`)
350
+ ];
351
+ for (const attemptPath of pathsToTry) try {
352
+ return await import(
353
+ /* @vite-ignore */
354
+ attemptPath
355
+ );
356
+ } catch {}
357
+ } catch {}
358
+ return null;
359
+ }
360
+ /**
361
+ * Resolves symlinks in node_modules to find the real package location
362
+ */
363
+ async function resolveSymlinkedPaths(packageName, subPath) {
364
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
365
+ const nodeModulesPatterns = [path.join(process.cwd(), "node_modules", packageName), path.join(process.cwd(), "node_modules", packageBaseName || packageName)];
366
+ const workspacePatterns = [];
367
+ for (const nodeModulesPath of nodeModulesPatterns) try {
368
+ const fs = await import("node:fs");
369
+ if (fs.existsSync(nodeModulesPath)) {
370
+ const realPath = fs.realpathSync(nodeModulesPath);
371
+ 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`));
372
+ }
373
+ } catch {}
374
+ return workspacePatterns;
375
+ }
376
+ /**
377
+ * Generates common workspace pattern paths
378
+ */
379
+ function getCommonWorkspacePaths(packageName, subPath) {
380
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
381
+ const commonRoots = [process.cwd(), path.dirname(process.cwd())];
382
+ const workspacePatterns = [];
383
+ 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`));
384
+ return workspacePatterns;
385
+ }
386
+ /**
387
+ * Attempts to import from a list of workspace patterns
388
+ */
389
+ async function tryWorkspacePatterns(patterns) {
390
+ for (const workspacePath of patterns) try {
391
+ return await import(
392
+ /* @vite-ignore */
393
+ workspacePath
394
+ );
395
+ } catch {}
396
+ return null;
397
+ }
398
+ /**
399
+ * Attempts to resolve linked packages using various fallback strategies
400
+ */
401
+ async function resolveLinkedPackage(packageName, subPath) {
402
+ let result = await tryNodeSuggestedPaths(packageName, subPath);
403
+ if (result) return result;
404
+ result = await tryImportMetaResolve(packageName, subPath);
405
+ if (result) return result;
406
+ result = await tryWorkspacePatterns(await resolveSymlinkedPaths(packageName, subPath));
407
+ if (result) return result;
408
+ result = await tryWorkspacePatterns(getCommonWorkspacePaths(packageName, subPath));
409
+ if (result) return result;
410
+ return null;
411
+ }
412
+ //#endregion
413
+ //#region src/packages/util.ts
414
+ childLogger(["reactor-api", "packages/util"]);
415
+ /**
416
+ * Tries to import document models from a package. This function cannot throw.
417
+ */
418
+ async function loadDocumentModels(packageName) {
419
+ return loadDependency(packageName, "document-models");
420
+ }
421
+ /**
422
+ * Tries to import subgraphs from a package. This function cannot throw.
423
+ */
424
+ async function loadSubgraphs(packageName) {
425
+ return loadDependency(packageName, "subgraphs");
426
+ }
427
+ /**
428
+ * Tries to import processors from a package. This function cannot throw.
429
+ */
430
+ async function loadProcessors(packageName) {
431
+ return loadDependency(packageName, "processors");
432
+ }
433
+ /**
434
+ * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.
435
+ * Returns null if the dependency cannot be loaded.
436
+ */
437
+ async function loadDependency(packageName, subPath) {
438
+ const fullPath = `${packageName}/${subPath}`;
439
+ try {
440
+ return await import(
441
+ /* @vite-ignore */
442
+ fullPath
443
+ );
444
+ } catch (e) {
445
+ if (e instanceof Error && "code" in e && (e.code === "ERR_MODULE_NOT_FOUND" || e.code === "ERR_UNSUPPORTED_DIR_IMPORT")) {
446
+ const result = await resolveLinkedPackage(packageName, subPath);
447
+ if (result) return result;
448
+ }
449
+ throw e;
450
+ }
451
+ }
452
+ function debounce(func, delay = 250) {
453
+ let timer;
454
+ return (immediate = false, ...args) => {
455
+ if (timer) clearTimeout(timer);
456
+ return new Promise((resolve, reject) => {
457
+ if (immediate) func(...args).then(resolve).catch(reject);
458
+ else timer = setTimeout(() => {
459
+ func(...args).then(resolve).catch(reject);
460
+ }, delay);
461
+ });
462
+ };
463
+ }
464
+ function isSubpath(parent, dir) {
465
+ const relative = path.relative(parent, dir);
466
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
467
+ }
468
+ //#endregion
469
+ //#region src/graphql/utils.ts
470
+ function isSubgraphClass(candidate) {
471
+ if (typeof candidate !== "function") return false;
472
+ let proto = Object.getPrototypeOf(candidate);
473
+ while (proto) {
474
+ if (Object.prototype.isPrototypeOf.call(proto, BaseSubgraph)) return true;
475
+ proto = Object.getPrototypeOf(proto);
476
+ }
477
+ return false;
478
+ }
479
+ function buildGraphqlOperations(operations, skip, first) {
480
+ return operations.slice(skip, skip + first).map(buildGraphqlOperation);
481
+ }
482
+ function buildGraphqlOperation(operation) {
483
+ const signer = operation.action.context?.signer;
484
+ return {
485
+ id: operation.id ?? "",
486
+ type: operation.action.type,
487
+ index: operation.index,
488
+ timestampUtcMs: operation.timestampUtcMs,
489
+ hash: operation.hash,
490
+ skip: operation.skip,
491
+ inputText: typeof operation.action.input === "string" ? operation.action.input : JSON.stringify(operation.action.input),
492
+ error: operation.error,
493
+ context: { signer: signer ? {
494
+ user: signer.user,
495
+ app: signer.app,
496
+ signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
497
+ } : void 0 }
498
+ };
499
+ }
500
+ function buildGraphQlDocument(doc) {
501
+ const state = doc.state;
502
+ const initialState = doc.initialState;
503
+ const globalState = "global" in doc.state ? doc.state.global : {};
504
+ return {
505
+ id: doc.header.id,
506
+ name: doc.header.name,
507
+ documentType: doc.header.documentType,
508
+ revision: doc.header.revision.global || 0,
509
+ createdAtUtcIso: doc.header.createdAtUtcIso,
510
+ lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,
511
+ operations: [],
512
+ stateJSON: globalState,
513
+ state,
514
+ initialState
515
+ };
516
+ }
517
+ function buildGraphQlDriveDocument(doc) {
518
+ return {
519
+ ...buildGraphQlDocument(doc),
520
+ meta: { preferredEditor: doc.header.meta?.preferredEditor },
521
+ slug: doc.header.slug,
522
+ state: doc.state.global,
523
+ initialState: doc.state.global
524
+ };
525
+ }
526
+ //#endregion
527
+ export { isSubgraphClass as a, loadDocumentModels as c, BaseSubgraph as d, AuthorizationPolicy as f, buildGraphqlOperations as i, loadProcessors as l, createAuthorizationService as m, buildGraphQlDriveDocument as n, debounce as o, AuthorizedDocumentHandle as p, buildGraphqlOperation as r, isSubpath as s, buildGraphQlDocument as t, loadSubgraphs as u };
528
+
529
+ //# sourceMappingURL=utils-Dh9tl892.mjs.map
530
+ //# debugId=02ee5aff-26c7-5e45-b81e-6ec7bce7f7ec