@party-stack/ontology-server 0.0.0-stage → 0.11.1

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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +493 -2
  3. package/lib/attachmentHttp.d.ts +15 -0
  4. package/lib/attachmentHttp.d.ts.map +1 -0
  5. package/lib/attachmentHttp.js +235 -0
  6. package/lib/attachmentHttp.js.map +1 -0
  7. package/lib/attachmentTransfers.d.ts +115 -0
  8. package/lib/attachmentTransfers.d.ts.map +1 -0
  9. package/lib/attachmentTransfers.js +208 -0
  10. package/lib/attachmentTransfers.js.map +1 -0
  11. package/lib/authorization.d.ts +21 -0
  12. package/lib/authorization.d.ts.map +1 -0
  13. package/lib/authorization.js +385 -0
  14. package/lib/authorization.js.map +1 -0
  15. package/lib/bindingFence.d.ts +27 -0
  16. package/lib/bindingFence.d.ts.map +1 -0
  17. package/lib/bindingFence.js +39 -0
  18. package/lib/bindingFence.js.map +1 -0
  19. package/lib/composition.d.ts +467 -0
  20. package/lib/composition.d.ts.map +1 -0
  21. package/lib/composition.js +102 -0
  22. package/lib/composition.js.map +1 -0
  23. package/lib/definitionProjection.d.ts +21 -0
  24. package/lib/definitionProjection.d.ts.map +1 -0
  25. package/lib/definitionProjection.js +441 -0
  26. package/lib/definitionProjection.js.map +1 -0
  27. package/lib/errorProjection.d.ts +22 -0
  28. package/lib/errorProjection.d.ts.map +1 -0
  29. package/lib/errorProjection.js +72 -0
  30. package/lib/errorProjection.js.map +1 -0
  31. package/lib/http.d.ts +23 -0
  32. package/lib/http.d.ts.map +1 -0
  33. package/lib/http.js +17 -0
  34. package/lib/http.js.map +1 -0
  35. package/lib/index.d.ts +5 -0
  36. package/lib/index.js +3 -0
  37. package/lib/internalAccess.d.ts +10 -0
  38. package/lib/internalAccess.d.ts.map +1 -0
  39. package/lib/internalAccess.js +18 -0
  40. package/lib/internalAccess.js.map +1 -0
  41. package/lib/operations.d.ts +1265 -0
  42. package/lib/operations.d.ts.map +1 -0
  43. package/lib/operations.js +621 -0
  44. package/lib/operations.js.map +1 -0
  45. package/lib/policyDefinition.d.ts +19 -0
  46. package/lib/policyDefinition.d.ts.map +1 -0
  47. package/lib/policyDefinition.js +226 -0
  48. package/lib/policyDefinition.js.map +1 -0
  49. package/lib/policyWatches.d.ts +17 -0
  50. package/lib/policyWatches.d.ts.map +1 -0
  51. package/lib/policyWatches.js +49 -0
  52. package/lib/policyWatches.js.map +1 -0
  53. package/lib/receiptPolicy.d.ts +12 -0
  54. package/lib/receiptPolicy.d.ts.map +1 -0
  55. package/lib/receiptPolicy.js +63 -0
  56. package/lib/receiptPolicy.js.map +1 -0
  57. package/lib/replicaBootstrap.d.ts +56 -0
  58. package/lib/replicaBootstrap.d.ts.map +1 -0
  59. package/lib/replicaBootstrap.js +60 -0
  60. package/lib/replicaBootstrap.js.map +1 -0
  61. package/lib/routing.d.ts +87 -0
  62. package/lib/routing.d.ts.map +1 -0
  63. package/lib/routing.js +344 -0
  64. package/lib/routing.js.map +1 -0
  65. package/lib/rpc.d.ts +4799 -0
  66. package/lib/rpc.d.ts.map +1 -0
  67. package/lib/rpc.js +575 -0
  68. package/lib/rpc.js.map +1 -0
  69. package/lib/rpcActivity.d.ts +6 -0
  70. package/lib/rpcActivity.d.ts.map +1 -0
  71. package/lib/rpcActivity.js +8 -0
  72. package/lib/rpcActivity.js.map +1 -0
  73. package/lib/rpcBackend.d.ts +8 -0
  74. package/lib/rpcBackend.d.ts.map +1 -0
  75. package/lib/rpcBackend.js +76 -0
  76. package/lib/rpcBackend.js.map +1 -0
  77. package/lib/rpcHttp.d.ts +24 -0
  78. package/lib/rpcHttp.d.ts.map +1 -0
  79. package/lib/rpcHttp.js +118 -0
  80. package/lib/rpcHttp.js.map +1 -0
  81. package/lib/rpcLocal.d.ts +13 -0
  82. package/lib/rpcLocal.d.ts.map +1 -0
  83. package/lib/rpcLocal.js +26 -0
  84. package/lib/rpcLocal.js.map +1 -0
  85. package/lib/rpcWatch.d.ts +9 -0
  86. package/lib/rpcWatch.d.ts.map +1 -0
  87. package/lib/rpcWatch.js +29 -0
  88. package/lib/rpcWatch.js.map +1 -0
  89. package/lib/rpcWorker.d.ts +38 -0
  90. package/lib/rpcWorker.d.ts.map +1 -0
  91. package/lib/rpcWorker.js +192 -0
  92. package/lib/rpcWorker.js.map +1 -0
  93. package/package.json +53 -3
@@ -0,0 +1,102 @@
1
+ import { validateContext } from "./policyDefinition.js";
2
+ import { projectOntologyBackend } from "./authorization.js";
3
+ import { withInternalCommands } from "./internalAccess.js";
4
+ import { ontologyRpcHandlers } from "./rpc.js";
5
+ import { BackendError, classifyBackendFailure } from "@party-stack/ontology-backend";
6
+ import { sliceByteSource } from "@party-stack/ontology-storage/blobs";
7
+ import { Effect, Layer, Schema } from "effect";
8
+ import { makeCachedProxy, replicaStateSource } from "@party-stack/ontology-replica/infrastructure";
9
+ //#region src/composition.ts
10
+ const prepareOntologyServer = Effect.fn("OntologyServer.prepare")(function* (options) {
11
+ let backend = options.backend;
12
+ let source;
13
+ if (options.kind === "cached-proxy") backend = yield* makeCachedProxy({
14
+ replica: options.cache,
15
+ backend
16
+ });
17
+ else if (options.kind === "replica") {
18
+ source = replicaStateSource(options.replica);
19
+ backend = replicaServerBackend(options.replica, backend);
20
+ }
21
+ const ir = options.ir ?? (options.kind === "owned" ? options.backend.storage.ir : options.kind === "replica" ? options.replica.ir : options.kind === "cached-proxy" ? options.cache.ir : void 0);
22
+ return {
23
+ ...options,
24
+ backend,
25
+ source,
26
+ ir,
27
+ context: options.kind === "replica" ? options.replica.context : void 0
28
+ };
29
+ });
30
+ const bindOntologyServer = Effect.fn("OntologyServer.bind")(function* (prepared, context, internalAccess) {
31
+ context ??= prepared.context;
32
+ if (prepared.ir?.policy) context ??= {};
33
+ if (context && prepared.ir) context = yield* validateContext(prepared.ir, context);
34
+ const allowInternal = typeof internalAccess === "function" ? yield* Effect.try({
35
+ try: () => internalAccess(context ?? {}),
36
+ catch: (cause) => classifyBackendFailure("server.internalAccess", cause)
37
+ }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Boolean)), Effect.mapError(() => new BackendError({
38
+ operation: "server.internalAccess",
39
+ kind: "InvalidConfiguration",
40
+ retryable: false,
41
+ message: "The internal-access predicate must return a boolean."
42
+ }))) : internalAccess === true;
43
+ if (!prepared.ir?.policy) {
44
+ if (allowInternal) return {
45
+ ...prepared,
46
+ context,
47
+ errors: "forward",
48
+ authorize: () => Effect.void
49
+ };
50
+ return yield* new BackendError({
51
+ operation: "server.bind",
52
+ kind: "InvalidConfiguration",
53
+ retryable: false,
54
+ message: "An endpoint requires an IR policy or explicit internal access."
55
+ });
56
+ }
57
+ const view = yield* projectOntologyBackend({
58
+ backend: prepared.backend,
59
+ ir: prepared.ir,
60
+ context
61
+ }, prepared.kind === "owned" ? "owned" : "upstream");
62
+ return {
63
+ ...prepared,
64
+ ...view,
65
+ errors: "projected",
66
+ source: void 0,
67
+ backend: {
68
+ ...view.backend,
69
+ maintenance: prepared.backend.maintenance
70
+ },
71
+ authorize: withInternalCommands(view.authorize, allowInternal)
72
+ };
73
+ });
74
+ /** Ordinary provider capabilities of a replica server; speculative state remains a separate extension. */
75
+ const replicaServerBackend = (replica, backend) => {
76
+ return {
77
+ ...backend,
78
+ supportsIdempotency: true,
79
+ attachments: {
80
+ stage: (value, bytes) => replica.attachments.create(bytes, { id: value.id }).pipe(Effect.map((created) => created.attachment)),
81
+ read: (value, range) => replica.attachments.source(value).pipe(Effect.map((source) => range ? sliceByteSource(source, range.offset ?? 0, range.length) : source)),
82
+ metadata: (value, settings) => replica.attachments.metadata(value, settings).pipe(Effect.map(({ name, dimensions, ...rest }) => ({
83
+ ...rest,
84
+ name: name ?? void 0,
85
+ dimensions: dimensions ?? void 0
86
+ })))
87
+ },
88
+ applyAction: (invocation) => Effect.gen(function* () {
89
+ for (const upload of invocation.attachmentUploads ?? []) yield* replica.attachments.create(upload.blob, { id: upload.attachment.id });
90
+ return yield* replica.actions.apply({
91
+ ...invocation,
92
+ attachmentUploads: void 0
93
+ }, { optimistic: true });
94
+ })
95
+ };
96
+ };
97
+ /** One role/policy composition for transports with an already authenticated binding. */
98
+ const ontologyServerHandlers = (options) => Layer.unwrap(prepareOntologyServer(options).pipe(Effect.flatMap((prepared) => bindOntologyServer(prepared, options.context, options.dangerouslyAllowInternalAccess)), Effect.map(ontologyRpcHandlers)));
99
+ //#endregion
100
+ export { bindOntologyServer, ontologyServerHandlers, prepareOntologyServer, replicaServerBackend };
101
+
102
+ //# sourceMappingURL=composition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composition.js","names":[],"sources":["../src/composition.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure } from \"@party-stack/ontology-backend\";\nimport { makeCachedProxy, replicaStateSource } from \"@party-stack/ontology-replica/infrastructure\";\nimport { sliceByteSource } from \"@party-stack/ontology-storage/blobs\";\nimport { Effect, Layer, Schema, Scope } from \"effect\";\nimport { projectOntologyBackend } from \"./authorization.js\";\nimport { withInternalCommands } from \"./internalAccess.js\";\nimport { validateContext } from \"./policyDefinition.js\";\nimport { ontologyRpcHandlers } from \"./rpc.js\";\nimport type { OntologyInternalAccess } from \"./internalAccess.js\";\nimport type { OntologyRpcServerOptions } from \"./rpc.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\nimport type { OwnedBackendService } from \"@party-stack/ontology-backend/owned\";\nimport type { OntologySource } from \"@party-stack/ontology-backend/protocol\";\nimport type { ReplicaService } from \"@party-stack/ontology-replica\";\n\nexport type OntologyAuthenticate<R = never> = (\n request: Request\n) => Effect.Effect<Record<string, unknown>, BackendError, R | Scope.Scope>;\nexport type { OntologyInternalAccess } from \"./internalAccess.js\";\n\ntype Common<R> = Omit<\n OntologyRpcServerOptions<R>,\n \"source\" | \"backend\" | \"authorize\" | \"context\" | \"replica\" | \"errors\"\n>;\ntype Role =\n | { readonly kind: \"owned\"; readonly backend: OwnedBackendService }\n | { readonly kind: \"proxy\"; readonly backend: OntologyBackendService }\n | {\n readonly kind: \"cached-proxy\";\n readonly backend: OntologyBackendService;\n readonly cache: ReplicaService;\n }\n | {\n readonly kind: \"replica\";\n readonly backend: OntologyBackendService;\n readonly replica: ReplicaService;\n readonly dangerouslyAllowInternalAccess: true;\n readonly context?: never;\n };\ntype Binding =\n | {\n readonly context: Record<string, unknown>;\n readonly dangerouslyAllowInternalAccess?: OntologyInternalAccess;\n }\n | { readonly context?: never; readonly dangerouslyAllowInternalAccess: true };\n\n/** Transport-neutral construction for an already authenticated principal or trusted peer. */\nexport type OntologyServerBindingOptions<R = never> = Common<R> & Role & Binding;\n/** HTTP authentication runs per request; internal commands require explicit opt-in. */\nexport type OntologyBindingOptions<R = never> = Common<R> &\n Role &\n (\n | (Binding & { readonly authenticate?: never })\n | {\n readonly context?: never;\n readonly dangerouslyAllowInternalAccess: true;\n readonly authenticate?: OntologyAuthenticate<R>;\n }\n | {\n readonly context?: never;\n readonly dangerouslyAllowInternalAccess?: OntologyInternalAccess;\n readonly authenticate: OntologyAuthenticate<R>;\n }\n );\n\n// Role composition is acquired once. In particular, every caller must share the\n// cached proxy's invalidation generation, backend owner and maintenance lifecycle.\nexport const prepareOntologyServer = Effect.fn(\"OntologyServer.prepare\")(function* <R>(\n options: Common<R> & Role\n) {\n let backend: OntologyBackendService = options.backend;\n let source: OntologySource | undefined;\n if (options.kind === \"cached-proxy\")\n backend = yield* makeCachedProxy({ replica: options.cache, backend });\n else if (options.kind === \"replica\") {\n source = replicaStateSource(options.replica);\n backend = replicaServerBackend(options.replica, backend);\n }\n const ir =\n options.ir ??\n (options.kind === \"owned\"\n ? options.backend.storage.ir\n : options.kind === \"replica\"\n ? options.replica.ir\n : options.kind === \"cached-proxy\"\n ? options.cache.ir\n : undefined);\n return {\n ...options,\n backend,\n source,\n ir,\n context: options.kind === \"replica\" ? options.replica.context : undefined,\n };\n});\n\nexport const bindOntologyServer = Effect.fn(\"OntologyServer.bind\")(function* <R>(\n prepared: Effect.Success<ReturnType<typeof prepareOntologyServer<R>>>,\n context: Record<string, unknown> | undefined,\n internalAccess: OntologyInternalAccess | undefined\n) {\n context ??= prepared.context;\n if (prepared.ir?.policy) context ??= {};\n if (context && prepared.ir) context = yield* validateContext(prepared.ir, context);\n const allowInternal =\n typeof internalAccess === \"function\"\n ? yield* Effect.try({\n try: () => internalAccess(context ?? {}),\n catch: (cause) => classifyBackendFailure(\"server.internalAccess\", cause),\n }).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Boolean)),\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"server.internalAccess\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"The internal-access predicate must return a boolean.\",\n })\n )\n )\n : internalAccess === true;\n if (!prepared.ir?.policy) {\n if (allowInternal)\n return { ...prepared, context, errors: \"forward\" as const, authorize: () => Effect.void };\n return yield* new BackendError({\n operation: \"server.bind\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"An endpoint requires an IR policy or explicit internal access.\",\n });\n }\n const view = yield* projectOntologyBackend(\n { backend: prepared.backend, ir: prepared.ir, context: context! },\n prepared.kind === \"owned\" ? \"owned\" : \"upstream\"\n );\n return {\n ...prepared,\n ...view,\n errors: \"projected\" as const,\n // Raw journals and speculative state are not policy-projected yet.\n source: undefined,\n backend: { ...view.backend, maintenance: prepared.backend.maintenance },\n authorize: withInternalCommands(view.authorize, allowInternal),\n };\n});\n\n/** Ordinary provider capabilities of a replica server; speculative state remains a separate extension. */\nexport const replicaServerBackend = (\n replica: ReplicaService,\n backend: OntologyBackendService\n): OntologyBackendService => {\n return {\n ...backend,\n supportsIdempotency: true,\n // The ordinary adapter facet stays committed: rows and cursors come\n // from upstream. Published predictions travel only through source.\n // Local staged/cached attachments still belong to this server.\n attachments: {\n stage: (value, bytes) =>\n replica.attachments\n .create(bytes, { id: value.id })\n .pipe(Effect.map((created) => created.attachment)),\n read: (value, range) =>\n replica.attachments\n .source(value)\n .pipe(\n Effect.map((source) =>\n range ? sliceByteSource(source, range.offset ?? 0, range.length) : source\n )\n ),\n metadata: (value, settings) =>\n replica.attachments.metadata(value, settings).pipe(\n Effect.map(({ name, dimensions, ...rest }) => ({\n ...rest,\n name: name ?? undefined,\n dimensions: dimensions ?? undefined,\n }))\n ),\n },\n applyAction: (invocation) =>\n Effect.gen(function* () {\n for (const upload of invocation.attachmentUploads ?? [])\n yield* replica.attachments.create(upload.blob, { id: upload.attachment.id });\n return yield* replica.actions.apply(\n { ...invocation, attachmentUploads: undefined },\n { optimistic: true }\n );\n }),\n };\n};\n\n/** One role/policy composition for transports with an already authenticated binding. */\nexport const ontologyServerHandlers = <R = never>(options: OntologyServerBindingOptions<R>) =>\n Layer.unwrap(\n prepareOntologyServer(options).pipe(\n Effect.flatMap((prepared) =>\n bindOntologyServer(prepared, options.context, options.dangerouslyAllowInternalAccess)\n ),\n Effect.map(ontologyRpcHandlers)\n )\n );\n"],"mappings":"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"}
@@ -0,0 +1,21 @@
1
+ import { Expression, OntologyDefinition, OntologyIR } from "@party-stack/ontology-spec";
2
+ //#region src/definitionProjection.d.ts
3
+ export type FixedActionParameterValue = Expression;
4
+ export type FixedActionParameterValues<Ontology extends OntologyDefinition = OntologyDefinition> = { [ActionTypeName in Extract<keyof Ontology["actionTypes"], string>]?: { [ParameterName in Extract<keyof Ontology["actionTypes"][ActionTypeName]["parameters"], string>]?: FixedActionParameterValue; }; };
5
+ export declare function projectOntologyDefinition<Ontology extends OntologyDefinition = OntologyDefinition>(opts: {
6
+ ir: OntologyIR;
7
+ context?: Record<string, unknown>;
8
+ fixedActionParameterValues?: FixedActionParameterValues<Ontology>;
9
+ projectFixedActionParameterValuesInDefaults?: boolean;
10
+ allowedObjectTypeProperties: Record<string, readonly string[]>;
11
+ /**
12
+ * Projects object/property/link/action/query visibility from the resolved
13
+ * authorization policy. Otherwise the full schema is retained while action
14
+ * parameters and logic are still projected.
15
+ */
16
+ filterSchemaByAuthorization?: boolean;
17
+ visibleActionTypes?: readonly string[] | "all";
18
+ visibleQueryFunctionTypes?: readonly string[] | "all";
19
+ }): OntologyIR;
20
+ //#endregion
21
+ //# sourceMappingURL=definitionProjection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definitionProjection.d.ts","names":[],"sources":["../src/definitionProjection.ts"],"mappings":";;YAgBY,4BAA4B;YAE5B,2BAA2B,iBAAiB,qBAAqB,yBACxE,kBAAkB,cAAc,uCAEzB,iBAAiB,cAAc,wBAAwB,0CACvD;wBAggBI,0BAA0B,iBAAiB,qBAAqB,oBAAoB;EAChG,IAAI;EAEJ,UAAU;EAEV,6BAA6B,2BAA2B;EACxD;EACA,6BAA6B;;;;;;EAM7B;EACA;EACA;IACA"}
@@ -0,0 +1,441 @@
1
+ import { isRelatedFromForeignKeySource, resolveLookupReference, resolveRelatedLink } from "@party-stack/ontology-spec/utils";
2
+ //#region src/definitionProjection.ts
3
+ function hasPath(value, path) {
4
+ let current = value;
5
+ for (const segment of path) {
6
+ if (typeof current !== "object" || current === null || !(segment in current)) return false;
7
+ current = current[segment];
8
+ }
9
+ return true;
10
+ }
11
+ function resolveType$1(ir, type) {
12
+ if (type.kind !== "ref") return type;
13
+ const namedType = ir.types.find((candidate) => candidate.name === type.value.name);
14
+ if (!namedType) throw new Error(`Unknown ontology type "${type.value.name}".`);
15
+ return resolveType$1(ir, namedType.type);
16
+ }
17
+ function getActionType(ir, actionTypeName) {
18
+ const actionType = ir.actionTypes.find((candidate) => candidate.name === actionTypeName);
19
+ if (!actionType) throw new Error(`Unknown action type "${actionTypeName}".`);
20
+ return actionType;
21
+ }
22
+ function getObjectReferenceObjectType(ir, actionType, reference) {
23
+ const parameter = actionType.parameters.find((candidate) => candidate.name === reference.name);
24
+ if (!parameter) throw new Error(`Unknown action parameter "${reference.name}".`);
25
+ const type = resolveType$1(ir, parameter.type);
26
+ if (type.kind !== "objectReference") throw new Error(`Action parameter "${parameter.name}" is not an object reference.`);
27
+ return type.value.objectType;
28
+ }
29
+ function getFixedActionParameterValues(fixedActionParameterValues, actionName) {
30
+ return fixedActionParameterValues?.[actionName];
31
+ }
32
+ function isActionParameterFixed(fixedActionParameterValues, actionName, parameterName) {
33
+ return getFixedActionParameterValues(fixedActionParameterValues, actionName)?.[parameterName] !== void 0;
34
+ }
35
+ function getVisibleActionParameterNames(actionTypeName, parameters, fixedActionParameterValues) {
36
+ return new Set(parameters.filter((parameter) => !isActionParameterFixed(fixedActionParameterValues, actionTypeName, parameter.name)).map((parameter) => parameter.name));
37
+ }
38
+ function getExpressionObjectType(ir, actionName, expression) {
39
+ if (expression.kind === "lookup") return resolveLookupReference(ir, expression.value.reference, getActionType(ir, actionName).parameters)?.objectType;
40
+ if (expression.kind === "related") {
41
+ const sourceObjectType = getExpressionObjectType(ir, actionName, expression.value.source);
42
+ if (!sourceObjectType) return void 0;
43
+ const link = resolveRelatedLink(ir, sourceObjectType, expression.value.link);
44
+ if (!link) return void 0;
45
+ const foreignKeyOnSource = isRelatedFromForeignKeySource(link, sourceObjectType, expression.value.link);
46
+ if (!foreignKeyOnSource && link.cardinality === "many") return;
47
+ return foreignKeyOnSource ? link.target.objectType : link.source.objectType;
48
+ }
49
+ }
50
+ function projectExpression(opts) {
51
+ switch (opts.expression.kind) {
52
+ case "contextReference": {
53
+ const { name } = opts.expression.value;
54
+ let type = opts.ir.context?.type;
55
+ while (type) {
56
+ type = resolveType$1(opts.ir, type);
57
+ if (type.kind !== "optional") break;
58
+ type = type.value.type;
59
+ }
60
+ return (type ? type.kind === "struct" && type.value.fields.some((field) => field.name === name) : hasPath(opts.context, [name])) ? opts.expression : void 0;
61
+ }
62
+ case "literal":
63
+ case "uuid":
64
+ case "now":
65
+ case "localReference": return opts.expression;
66
+ case "getAt": {
67
+ const objectType = getExpressionObjectType(opts.ir, opts.actionName, opts.expression.value.source);
68
+ if (objectType && !(opts.allowedObjectTypeProperties[objectType] ?? []).includes(opts.expression.value.path[0])) return;
69
+ const source = projectExpression({
70
+ ...opts,
71
+ expression: opts.expression.value.source
72
+ });
73
+ return source ? {
74
+ kind: "getAt",
75
+ value: {
76
+ source,
77
+ path: opts.expression.value.path
78
+ }
79
+ } : void 0;
80
+ }
81
+ case "lookup": {
82
+ const reference = projectExpression({
83
+ ...opts,
84
+ expression: opts.expression.value.reference
85
+ });
86
+ return reference ? {
87
+ kind: "lookup",
88
+ value: { reference }
89
+ } : void 0;
90
+ }
91
+ case "related": {
92
+ const source = projectExpression({
93
+ ...opts,
94
+ expression: opts.expression.value.source
95
+ });
96
+ return source && getExpressionObjectType(opts.ir, opts.actionName, opts.expression) ? {
97
+ kind: "related",
98
+ value: {
99
+ source,
100
+ link: opts.expression.value.link
101
+ }
102
+ } : void 0;
103
+ }
104
+ case "struct": {
105
+ const fields = opts.expression.value.fields.map((field) => ({
106
+ ...field,
107
+ value: projectExpression({
108
+ ...opts,
109
+ expression: field.value
110
+ })
111
+ }));
112
+ return fields.some((field) => field.value === void 0) ? void 0 : {
113
+ kind: "struct",
114
+ value: { fields }
115
+ };
116
+ }
117
+ case "map": {
118
+ const source = projectExpression({
119
+ ...opts,
120
+ expression: opts.expression.value.source
121
+ });
122
+ const body = projectExpression({
123
+ ...opts,
124
+ expression: opts.expression.value.body
125
+ });
126
+ return source && body ? {
127
+ kind: "map",
128
+ value: {
129
+ source,
130
+ binding: opts.expression.value.binding,
131
+ body
132
+ }
133
+ } : void 0;
134
+ }
135
+ case "inputReference": {
136
+ const parameterName = opts.expression.value.name;
137
+ if (opts.visibleParameters.has(parameterName)) return opts.expression;
138
+ if (!opts.projectFixedParameterValues) return;
139
+ const fixedValue = getFixedActionParameterValues(opts.fixedActionParameterValues, opts.actionName)?.[parameterName];
140
+ if (fixedValue === void 0) return void 0;
141
+ if (fixedValue.kind === "inputReference" && fixedValue.value.name === parameterName) return;
142
+ return projectExpression({
143
+ ...opts,
144
+ expression: fixedValue
145
+ });
146
+ }
147
+ case "case": {
148
+ const branches = opts.expression.value.branches.map((branch) => ({
149
+ condition: projectExpression({
150
+ ...opts,
151
+ expression: branch.condition
152
+ }),
153
+ result: projectExpression({
154
+ ...opts,
155
+ expression: branch.result
156
+ })
157
+ }));
158
+ const otherwise = projectExpression({
159
+ ...opts,
160
+ expression: opts.expression.value.else
161
+ });
162
+ return otherwise && branches.every((b) => b.condition && b.result) ? {
163
+ kind: "case",
164
+ value: {
165
+ branches,
166
+ else: otherwise
167
+ }
168
+ } : void 0;
169
+ }
170
+ case "not": {
171
+ const expression = projectExpression({
172
+ ...opts,
173
+ expression: opts.expression.value.expression
174
+ });
175
+ return expression ? {
176
+ kind: "not",
177
+ value: { expression }
178
+ } : void 0;
179
+ }
180
+ case "and":
181
+ case "or":
182
+ case "concat":
183
+ case "coalesce": {
184
+ const expressions = opts.expression.value.expressions.map((expression) => projectExpression({
185
+ ...opts,
186
+ expression
187
+ }));
188
+ return expressions.every((e) => e !== void 0) ? {
189
+ kind: opts.expression.kind,
190
+ value: { expressions }
191
+ } : void 0;
192
+ }
193
+ case "eq":
194
+ case "ne":
195
+ case "lt":
196
+ case "lte":
197
+ case "gt":
198
+ case "gte":
199
+ case "in":
200
+ case "contains":
201
+ case "like":
202
+ case "ilike":
203
+ case "add":
204
+ case "subtract":
205
+ case "multiply":
206
+ case "divide": {
207
+ const left = projectExpression({
208
+ ...opts,
209
+ expression: opts.expression.value.left
210
+ });
211
+ const right = projectExpression({
212
+ ...opts,
213
+ expression: opts.expression.value.right
214
+ });
215
+ return left && right ? {
216
+ kind: opts.expression.kind,
217
+ value: {
218
+ left,
219
+ right
220
+ }
221
+ } : void 0;
222
+ }
223
+ case "exists": return;
224
+ }
225
+ }
226
+ function projectAssignments(opts) {
227
+ const allowedProperties = opts.allowedObjectTypeProperties[opts.objectTypeName] ?? [];
228
+ return opts.assignments.flatMap((assignment) => {
229
+ const propertyName = assignment.property[0];
230
+ if (!propertyName || !allowedProperties.includes(propertyName)) return [];
231
+ const projectedValue = projectExpression({
232
+ expression: assignment.value,
233
+ context: opts.context,
234
+ ir: opts.ir,
235
+ actionName: opts.actionName,
236
+ visibleParameters: opts.visibleParameters,
237
+ fixedActionParameterValues: opts.fixedActionParameterValues,
238
+ allowedObjectTypeProperties: opts.allowedObjectTypeProperties,
239
+ projectFixedParameterValues: true
240
+ });
241
+ return projectedValue ? [{
242
+ ...assignment,
243
+ value: projectedValue
244
+ }] : [];
245
+ });
246
+ }
247
+ function projectLogicStep(opts) {
248
+ switch (opts.step.kind) {
249
+ case "createObject": {
250
+ const values = projectAssignments({
251
+ assignments: opts.step.value.values,
252
+ context: opts.context,
253
+ ir: opts.ir,
254
+ actionName: opts.actionType.name,
255
+ objectTypeName: opts.step.value.objectType,
256
+ visibleParameters: opts.visibleParameters,
257
+ fixedActionParameterValues: opts.fixedActionParameterValues,
258
+ allowedObjectTypeProperties: opts.allowedObjectTypeProperties
259
+ });
260
+ return {
261
+ ...opts.step,
262
+ value: {
263
+ ...opts.step.value,
264
+ values
265
+ }
266
+ };
267
+ }
268
+ case "updateObject": {
269
+ const objectTypeName = getObjectReferenceObjectType(opts.ir, opts.actionType, opts.step.value.object);
270
+ const values = projectAssignments({
271
+ assignments: opts.step.value.values,
272
+ context: opts.context,
273
+ ir: opts.ir,
274
+ actionName: opts.actionType.name,
275
+ objectTypeName,
276
+ visibleParameters: opts.visibleParameters,
277
+ fixedActionParameterValues: opts.fixedActionParameterValues,
278
+ allowedObjectTypeProperties: opts.allowedObjectTypeProperties
279
+ });
280
+ return {
281
+ ...opts.step,
282
+ value: {
283
+ ...opts.step.value,
284
+ values
285
+ }
286
+ };
287
+ }
288
+ case "deleteObject": return opts.step;
289
+ }
290
+ }
291
+ function typeReferencesObjectTypes(type, ir, seen = /* @__PURE__ */ new Set()) {
292
+ if (type.kind === "ref") {
293
+ if (seen.has(type.value.name)) return /* @__PURE__ */ new Set();
294
+ seen.add(type.value.name);
295
+ const named = ir.types.find((candidate) => candidate.name === type.value.name);
296
+ return named ? typeReferencesObjectTypes(named.type, ir, seen) : /* @__PURE__ */ new Set();
297
+ }
298
+ switch (type.kind) {
299
+ case "objectReference": return /* @__PURE__ */ new Set([type.value.objectType]);
300
+ case "optional": return typeReferencesObjectTypes(type.value.type, ir, seen);
301
+ case "list": return typeReferencesObjectTypes(type.value.elementType, ir, seen);
302
+ case "map": {
303
+ const names = typeReferencesObjectTypes(type.value.keyType, ir, seen);
304
+ for (const name of typeReferencesObjectTypes(type.value.valueType, ir, seen)) names.add(name);
305
+ return names;
306
+ }
307
+ case "result": {
308
+ const names = typeReferencesObjectTypes(type.value.okType, ir, seen);
309
+ for (const name of typeReferencesObjectTypes(type.value.errType, ir, seen)) names.add(name);
310
+ return names;
311
+ }
312
+ case "struct": {
313
+ const names = /* @__PURE__ */ new Set();
314
+ for (const field of type.value.fields) for (const name of typeReferencesObjectTypes(field.type, ir, seen)) names.add(name);
315
+ return names;
316
+ }
317
+ case "union": {
318
+ const names = /* @__PURE__ */ new Set();
319
+ for (const variant of type.value.variants) for (const name of typeReferencesObjectTypes(variant.type, ir, seen)) names.add(name);
320
+ return names;
321
+ }
322
+ default: return /* @__PURE__ */ new Set();
323
+ }
324
+ }
325
+ function collectReferencedNamedTypes(type, ir, into, seen = /* @__PURE__ */ new Set()) {
326
+ if (type.kind === "ref") {
327
+ if (seen.has(type.value.name)) return;
328
+ seen.add(type.value.name);
329
+ into.add(type.value.name);
330
+ const named = ir.types.find((candidate) => candidate.name === type.value.name);
331
+ if (named) collectReferencedNamedTypes(named.type, ir, into, seen);
332
+ return;
333
+ }
334
+ switch (type.kind) {
335
+ case "optional":
336
+ collectReferencedNamedTypes(type.value.type, ir, into, seen);
337
+ break;
338
+ case "list":
339
+ collectReferencedNamedTypes(type.value.elementType, ir, into, seen);
340
+ break;
341
+ case "map":
342
+ collectReferencedNamedTypes(type.value.keyType, ir, into, seen);
343
+ collectReferencedNamedTypes(type.value.valueType, ir, into, seen);
344
+ break;
345
+ case "result":
346
+ collectReferencedNamedTypes(type.value.okType, ir, into, seen);
347
+ collectReferencedNamedTypes(type.value.errType, ir, into, seen);
348
+ break;
349
+ case "struct":
350
+ for (const field of type.value.fields) collectReferencedNamedTypes(field.type, ir, into, seen);
351
+ break;
352
+ case "union": for (const variant of type.value.variants) collectReferencedNamedTypes(variant.type, ir, into, seen);
353
+ }
354
+ }
355
+ function actionParametersReferenceHiddenObjectType(actionType, ir, visibleObjectTypes, visibleParameters) {
356
+ for (const parameter of actionType.parameters) {
357
+ if (visibleParameters && !visibleParameters.has(parameter.name)) continue;
358
+ for (const objectType of typeReferencesObjectTypes(parameter.type, ir)) if (!visibleObjectTypes.has(objectType)) return true;
359
+ }
360
+ return false;
361
+ }
362
+ function projectOntologyDefinition(opts) {
363
+ const filterSchemaByAuthorization = opts.filterSchemaByAuthorization ?? false;
364
+ const visibleObjectTypes = new Set(filterSchemaByAuthorization ? Object.entries(opts.allowedObjectTypeProperties).filter(([, properties]) => properties.length > 0).map(([objectType]) => objectType) : opts.ir.objectTypes.map((objectType) => objectType.name));
365
+ const objectTypes = filterSchemaByAuthorization ? opts.ir.objectTypes.filter((objectType) => visibleObjectTypes.has(objectType.name)).map((objectType) => {
366
+ const allowed = new Set(opts.allowedObjectTypeProperties[objectType.name] ?? []);
367
+ return {
368
+ ...objectType,
369
+ title: objectType.title && allowed.has(objectType.title) ? objectType.title : void 0,
370
+ properties: objectType.properties.filter((property) => allowed.has(property.name))
371
+ };
372
+ }) : opts.ir.objectTypes;
373
+ const linkTypes = filterSchemaByAuthorization ? opts.ir.linkTypes.filter((link) => {
374
+ if (!visibleObjectTypes.has(link.source.objectType) || !visibleObjectTypes.has(link.target.objectType)) return false;
375
+ if (!link.foreignKey) return true;
376
+ const sourceAllowed = new Set(opts.allowedObjectTypeProperties[link.source.objectType] ?? []);
377
+ const targetAllowed = new Set(opts.allowedObjectTypeProperties[link.target.objectType] ?? []);
378
+ return sourceAllowed.has(link.foreignKey) || targetAllowed.has(link.foreignKey);
379
+ }) : opts.ir.linkTypes;
380
+ const actionTypes = (opts.visibleActionTypes === void 0 || opts.visibleActionTypes === "all" ? opts.ir.actionTypes : opts.ir.actionTypes.filter((actionType) => opts.visibleActionTypes.includes(actionType.name))).filter((actionType) => !filterSchemaByAuthorization || !actionParametersReferenceHiddenObjectType(actionType, opts.ir, visibleObjectTypes, getVisibleActionParameterNames(actionType.name, actionType.parameters, opts.fixedActionParameterValues))).map((actionType) => {
381
+ const visibleParameters = getVisibleActionParameterNames(actionType.name, actionType.parameters, opts.fixedActionParameterValues);
382
+ return {
383
+ ...actionType,
384
+ parameters: actionType.parameters.filter((parameter) => visibleParameters.has(parameter.name)).map((parameter) => ({
385
+ ...parameter,
386
+ defaultValue: parameter.defaultValue ? projectExpression({
387
+ expression: parameter.defaultValue,
388
+ context: opts.context,
389
+ ir: opts.ir,
390
+ actionName: actionType.name,
391
+ visibleParameters,
392
+ fixedActionParameterValues: opts.fixedActionParameterValues,
393
+ allowedObjectTypeProperties: opts.allowedObjectTypeProperties,
394
+ projectFixedParameterValues: opts.projectFixedActionParameterValuesInDefaults ?? false
395
+ }) : void 0
396
+ })),
397
+ logic: actionType.logic.flatMap((step) => {
398
+ if (filterSchemaByAuthorization && step.kind === "createObject" && !visibleObjectTypes.has(step.value.objectType)) return [];
399
+ const projectedStep = projectLogicStep({
400
+ step,
401
+ context: opts.context,
402
+ ir: opts.ir,
403
+ actionType,
404
+ visibleParameters,
405
+ fixedActionParameterValues: opts.fixedActionParameterValues,
406
+ allowedObjectTypeProperties: opts.allowedObjectTypeProperties
407
+ });
408
+ return projectedStep ? [projectedStep] : [];
409
+ })
410
+ };
411
+ });
412
+ const queryFunctionTypes = opts.visibleQueryFunctionTypes === void 0 || opts.visibleQueryFunctionTypes === "all" ? opts.ir.queryFunctionTypes.filter((queryFunction) => {
413
+ if (!filterSchemaByAuthorization) return true;
414
+ for (const parameter of queryFunction.parameters) for (const objectType of typeReferencesObjectTypes(parameter.type, opts.ir)) if (!visibleObjectTypes.has(objectType)) return false;
415
+ for (const objectType of typeReferencesObjectTypes(queryFunction.returnType, opts.ir)) if (!visibleObjectTypes.has(objectType)) return false;
416
+ return true;
417
+ }) : opts.ir.queryFunctionTypes.filter((queryFunction) => opts.visibleQueryFunctionTypes.includes(queryFunction.name));
418
+ const referencedNamedTypes = /* @__PURE__ */ new Set();
419
+ if (opts.ir.context?.type) collectReferencedNamedTypes(opts.ir.context.type, opts.ir, referencedNamedTypes);
420
+ for (const objectType of objectTypes) for (const property of objectType.properties) collectReferencedNamedTypes(property.type, opts.ir, referencedNamedTypes);
421
+ for (const actionType of actionTypes) {
422
+ for (const parameter of actionType.parameters) collectReferencedNamedTypes(parameter.type, opts.ir, referencedNamedTypes);
423
+ if (actionType.returnType) collectReferencedNamedTypes(actionType.returnType, opts.ir, referencedNamedTypes);
424
+ }
425
+ for (const queryFunction of queryFunctionTypes) {
426
+ for (const parameter of queryFunction.parameters) collectReferencedNamedTypes(parameter.type, opts.ir, referencedNamedTypes);
427
+ collectReferencedNamedTypes(queryFunction.returnType, opts.ir, referencedNamedTypes);
428
+ }
429
+ return {
430
+ ...opts.ir,
431
+ types: filterSchemaByAuthorization ? opts.ir.types.filter((type) => referencedNamedTypes.has(type.name)) : opts.ir.types,
432
+ objectTypes,
433
+ linkTypes,
434
+ actionTypes,
435
+ queryFunctionTypes
436
+ };
437
+ }
438
+ //#endregion
439
+ export { projectOntologyDefinition };
440
+
441
+ //# sourceMappingURL=definitionProjection.js.map