@frontal-labs/ontology 0.0.1 → 1.0.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.
package/dist/index.js CHANGED
@@ -1,25 +1,8 @@
1
1
  "use strict";
2
2
  var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
6
  var __export = (target, all) => {
24
7
  for (var name in all)
25
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -33,30 +16,11 @@ var __copyProps = (to, from, except, desc) => {
33
16
  return to;
34
17
  };
35
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
- var __async = (__this, __arguments, generator) => {
37
- return new Promise((resolve, reject) => {
38
- var fulfilled = (value) => {
39
- try {
40
- step(generator.next(value));
41
- } catch (e) {
42
- reject(e);
43
- }
44
- };
45
- var rejected = (value) => {
46
- try {
47
- step(generator.throw(value));
48
- } catch (e) {
49
- reject(e);
50
- }
51
- };
52
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
- step((generator = generator.apply(__this, __arguments)).next());
54
- });
55
- };
56
19
 
57
20
  // src/index.ts
58
21
  var index_exports = {};
59
22
  __export(index_exports, {
23
+ DEFAULT_ONTOLOGY_BASE_URL: () => DEFAULT_ONTOLOGY_BASE_URL,
60
24
  FieldDefinitionSchema: () => FieldDefinitionSchema,
61
25
  FieldTypeSchema: () => FieldTypeSchema,
62
26
  IndexDefinitionSchema: () => IndexDefinitionSchema,
@@ -64,392 +28,2099 @@ __export(index_exports, {
64
28
  MixinDefinitionSchema: () => MixinDefinitionSchema,
65
29
  ModelDefinitionSchema: () => ModelDefinitionSchema,
66
30
  ModelSchema: () => ModelSchema,
67
- OntologyService: () => OntologyService,
31
+ OntologySdk: () => OntologySdk,
68
32
  RelationshipDefinitionSchema: () => RelationshipDefinitionSchema,
69
33
  RelationshipTypeSchema: () => RelationshipTypeSchema,
70
34
  RuleDefinitionSchema: () => RuleDefinitionSchema,
71
35
  SemanticMetadataSchema: () => SemanticMetadataSchema,
72
36
  SubstrateRoutingSchema: () => SubstrateRoutingSchema,
37
+ VERSION: () => VERSION,
73
38
  createOntologyClient: () => createOntologyClient,
74
39
  ontology: () => ontology
75
40
  });
76
41
  module.exports = __toCommonJS(index_exports);
77
- var import_core3 = require("@frontal-labs/core");
78
-
79
- // src/service.ts
80
- var import_core2 = require("@frontal-labs/core");
81
42
 
82
- // src/schemas.ts
83
- var import_core = require("@frontal-labs/core");
43
+ // ../core/dist/index.js
84
44
  var import_zod = require("zod");
85
- var FieldTypeSchema = import_zod.z.enum([
86
- "string",
87
- "integer",
88
- "float",
89
- "boolean",
90
- "uuid",
91
- "timestamp",
92
- "currency",
93
- "json",
94
- "array",
95
- "enum",
96
- "vector",
97
- "text"
98
- ]);
99
- var RelationshipTypeSchema = import_zod.z.enum([
100
- "hasOne",
101
- "hasMany",
102
- "belongsTo",
103
- "manyToMany"
104
- ]);
105
- var FieldDefinitionSchema = import_zod.z.object({
106
- type: FieldTypeSchema,
107
- required: import_zod.z.boolean().default(false),
108
- primary: import_zod.z.boolean().default(false),
109
- unique: import_zod.z.boolean().default(false),
110
- default: import_zod.z.unknown().optional(),
111
- substrate: import_zod.z.string().optional(),
112
- computed: import_zod.z.boolean().optional(),
113
- derivedBy: import_zod.z.string().optional(),
114
- cache: import_zod.z.object({
115
- ttl: import_zod.z.string()
116
- }).optional(),
117
- auto: import_zod.z.boolean().optional(),
118
- enum: import_zod.z.array(import_zod.z.string()).optional(),
119
- dimensions: import_zod.z.number().int().optional(),
120
- items: import_zod.z.string().optional(),
121
- description: import_zod.z.string().optional()
122
- }).passthrough();
123
- var RelationshipDefinitionSchema = import_zod.z.object({
124
- name: import_zod.z.string().optional(),
125
- type: RelationshipTypeSchema,
126
- targetEntity: import_zod.z.string(),
127
- foreignKey: import_zod.z.string().optional(),
128
- substrate: import_zod.z.string().optional(),
129
- cascade: import_zod.z.object({
130
- delete: import_zod.z.enum(["hard", "soft", "restrict", "nullify"]),
131
- update: import_zod.z.enum(["cascade", "restrict"])
132
- }).optional(),
133
- computed: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
134
- description: import_zod.z.string().optional()
135
- }).passthrough();
136
- var SubstrateRoutingSchema = import_zod.z.object({
137
- operational: import_zod.z.string().optional(),
138
- analytical: import_zod.z.string().optional(),
139
- semantic: import_zod.z.string().optional(),
140
- cache: import_zod.z.string().optional()
141
- }).passthrough();
142
- var SemanticMetadataSchema = import_zod.z.object({
143
- description: import_zod.z.string().optional(),
144
- lifecycle: import_zod.z.array(import_zod.z.string()).optional(),
145
- criticalFields: import_zod.z.array(import_zod.z.string()).optional(),
146
- significantEvents: import_zod.z.array(import_zod.z.string()).optional(),
147
- tags: import_zod.z.array(import_zod.z.string()).optional()
148
- }).passthrough();
149
- var IndexDefinitionSchema = import_zod.z.object({
150
- name: import_zod.z.string().optional(),
151
- fields: import_zod.z.array(import_zod.z.string()).min(1),
45
+
46
+ // ../../node_modules/.bun/@t3-oss+env-core@0.13.11+dcb9db7a51b27bde/node_modules/@t3-oss/env-core/dist/standard.js
47
+ function ensureSynchronous(value, message) {
48
+ if (value instanceof Promise) throw new Error(message);
49
+ }
50
+ function parseWithDictionary(dictionary, value) {
51
+ const result = {};
52
+ const issues = [];
53
+ for (const key in dictionary) {
54
+ const propResult = dictionary[key]["~standard"].validate(value[key]);
55
+ ensureSynchronous(propResult, `Validation must be synchronous, but ${key} returned a Promise.`);
56
+ if (propResult.issues) {
57
+ issues.push(...propResult.issues.map((issue) => ({
58
+ ...issue,
59
+ message: issue.message,
60
+ path: [key, ...issue.path ?? []]
61
+ })));
62
+ continue;
63
+ }
64
+ result[key] = propResult.value;
65
+ }
66
+ if (issues.length) return { issues };
67
+ return { value: result };
68
+ }
69
+
70
+ // ../../node_modules/.bun/@t3-oss+env-core@0.13.11+dcb9db7a51b27bde/node_modules/@t3-oss/env-core/dist/index.js
71
+ function createEnv(opts) {
72
+ const runtimeEnv = opts.runtimeEnvStrict ?? opts.runtimeEnv ?? process.env;
73
+ if (opts.emptyStringAsUndefined ?? false) {
74
+ for (const [key, value] of Object.entries(runtimeEnv)) if (value === "") delete runtimeEnv[key];
75
+ }
76
+ if (!!opts.skipValidation) {
77
+ if (opts.extends) for (const preset of opts.extends) preset.skipValidation = true;
78
+ return runtimeEnv;
79
+ }
80
+ const _client = typeof opts.client === "object" ? opts.client : {};
81
+ const _server = typeof opts.server === "object" ? opts.server : {};
82
+ const _shared = typeof opts.shared === "object" ? opts.shared : {};
83
+ const isServer = opts.isServer ?? (typeof window === "undefined" || "Deno" in window);
84
+ const finalSchemaShape = isServer ? {
85
+ ..._server,
86
+ ..._shared,
87
+ ..._client
88
+ } : {
89
+ ..._client,
90
+ ..._shared
91
+ };
92
+ const parsed = opts.createFinalSchema?.(finalSchemaShape, isServer)?.["~standard"].validate(runtimeEnv) ?? parseWithDictionary(finalSchemaShape, runtimeEnv);
93
+ ensureSynchronous(parsed, "Validation must be synchronous");
94
+ const onValidationError = opts.onValidationError ?? ((issues) => {
95
+ console.error("\u274C Invalid environment variables:", issues);
96
+ throw new Error("Invalid environment variables");
97
+ });
98
+ const onInvalidAccess = opts.onInvalidAccess ?? (() => {
99
+ throw new Error("\u274C Attempted to access a server-side environment variable on the client");
100
+ });
101
+ if (parsed.issues) return onValidationError(parsed.issues);
102
+ const isServerAccess = (prop) => {
103
+ if (!opts.clientPrefix) return true;
104
+ return !prop.startsWith(opts.clientPrefix) && !(prop in _shared);
105
+ };
106
+ const isValidServerAccess = (prop) => {
107
+ return isServer || !isServerAccess(prop);
108
+ };
109
+ const ignoreProp = (prop) => {
110
+ return prop === "__esModule" || prop === "$$typeof";
111
+ };
112
+ const extendedObj = (opts.extends ?? []).reduce((acc, curr) => {
113
+ return Object.assign(acc, curr);
114
+ }, {});
115
+ const fullObj = Object.assign(extendedObj, parsed.value);
116
+ return new Proxy(fullObj, { get(target, prop) {
117
+ if (typeof prop !== "string") return void 0;
118
+ if (ignoreProp(prop)) return void 0;
119
+ if (!isValidServerAccess(prop)) return onInvalidAccess(prop);
120
+ return Reflect.get(target, prop);
121
+ } });
122
+ }
123
+
124
+ // ../core/dist/index.js
125
+ var import_zod2 = require("zod");
126
+ var import_zod3 = require("zod");
127
+ var import_zod4 = require("zod");
128
+ var DEFAULT_BASE_URL = "https://api.frontal.dev/v1";
129
+ var API_KEY_PREFIX = "frt_";
130
+ var BACKOFF_STRATEGIES = [
131
+ "exponential",
132
+ "linear",
133
+ "constant"
134
+ ];
135
+ var DEFAULT_RETRY_ON = [429, 500, 502, 503, 504];
136
+ var EXPONENTIAL_BASE = 2;
137
+ var JITTER_MAX = 200;
138
+ var SDK_VERSION = "1.0.1";
139
+ var timestampSchema = import_zod.z.date().transform((date) => new Date(date));
140
+ var responseMetaSchema = import_zod.z.object({
141
+ requestId: import_zod.z.string().min(1),
142
+ timestamp: timestampSchema,
143
+ version: import_zod.z.string().optional(),
152
144
  substrate: import_zod.z.string().optional(),
153
- unique: import_zod.z.boolean().default(false),
154
- type: import_zod.z.enum(["btree", "hash", "gin", "gist", "brin"]).default("btree")
155
- }).passthrough();
156
- var ModelDefinitionSchema = import_zod.z.object({
157
- name: import_zod.z.string(),
158
- displayName: import_zod.z.string().optional(),
159
- description: import_zod.z.string().optional(),
160
- extends: import_zod.z.string().optional(),
161
- mixins: import_zod.z.array(import_zod.z.string()).optional(),
162
- fields: import_zod.z.record(import_zod.z.string(), FieldDefinitionSchema),
163
- relationships: import_zod.z.record(import_zod.z.string(), RelationshipDefinitionSchema).optional(),
164
- substrates: SubstrateRoutingSchema.optional(),
165
- semantics: SemanticMetadataSchema.optional(),
166
- indexes: import_zod.z.array(IndexDefinitionSchema).optional(),
167
- status: import_zod.z.enum(["draft", "active", "deprecated"]).default("draft")
145
+ latency: import_zod.z.object({
146
+ total: import_zod.z.number().int().min(0),
147
+ substrate: import_zod.z.number().int().min(0).optional()
148
+ }).optional()
168
149
  }).strict();
169
- var ModelSchema = ModelDefinitionSchema.extend({
170
- id: import_zod.z.string(),
171
- version: import_zod.z.number().int(),
172
- createdAt: import_core.timestampSchema,
173
- updatedAt: import_core.timestampSchema,
174
- entityCount: import_zod.z.number().int().optional()
175
- }).passthrough();
176
- var MigrationPlanSchema = import_zod.z.object({
177
- id: import_zod.z.string(),
178
- modelId: import_zod.z.string(),
179
- fromVersion: import_zod.z.number().int(),
180
- toVersion: import_zod.z.number().int(),
181
- changes: import_zod.z.array(
182
- import_zod.z.object({
183
- type: import_zod.z.enum([
184
- "add-field",
185
- "remove-field",
186
- "modify-field",
187
- "add-relationship",
188
- "remove-relationship"
189
- ]),
190
- description: import_zod.z.string(),
191
- impact: import_zod.z.enum(["breaking", "non-breaking", "data-loss"]),
192
- sql: import_zod.z.string().optional()
193
- })
194
- ),
195
- riskLevel: import_zod.z.enum(["low", "medium", "high", "critical"]),
196
- estimatedDowntime: import_zod.z.string().optional(),
197
- rolloutStrategy: import_zod.z.enum([
198
- "zero-downtime",
199
- "maintenance-window",
200
- "immediate"
201
- ]),
202
- createdAt: import_core.timestampSchema
203
- }).passthrough();
204
- var RuleDefinitionSchema = import_zod.z.object({
205
- name: import_zod.z.string(),
206
- description: import_zod.z.string().optional(),
207
- entityTypes: import_zod.z.array(import_zod.z.string()).min(1),
208
- condition: import_zod.z.string(),
209
- action: import_zod.z.enum(["validate", "transform", "notify"]),
210
- severity: import_zod.z.enum(["error", "warning", "info"]),
211
- enabled: import_zod.z.boolean().default(true)
150
+ var paginationMetaSchema = import_zod.z.object({
151
+ cursor: import_zod.z.string().min(1),
152
+ hasMore: import_zod.z.boolean(),
153
+ limit: import_zod.z.number().int().positive().optional(),
154
+ total: import_zod.z.number().int().min(0).optional(),
155
+ offset: import_zod.z.number().int().min(0).optional()
212
156
  }).strict();
213
- var MixinDefinitionSchema = import_zod.z.object({
214
- name: import_zod.z.string(),
215
- description: import_zod.z.string().optional(),
216
- fields: import_zod.z.record(import_zod.z.string(), FieldDefinitionSchema),
217
- relationships: import_zod.z.record(import_zod.z.string(), RelationshipDefinitionSchema).optional(),
218
- appliesTo: import_zod.z.array(import_zod.z.string()).optional()
157
+ var errorFieldSchema = import_zod.z.object({
158
+ field: import_zod.z.string().describe("Field name"),
159
+ code: import_zod.z.string().describe("Error code"),
160
+ message: import_zod.z.string().describe("Error message")
219
161
  }).strict();
220
-
221
- // src/service.ts
222
- var asPagePayload = (raw) => raw;
223
- var OntologyService = class {
224
- constructor(http) {
225
- this.http = http;
226
- this.migrations = new MigrationsNamespace(this.http);
227
- this.rules = new RulesNamespace(this.http);
228
- this.mixins = new MixinsNamespace(this.http);
229
- this.generation = new GenerationNamespace(this.http);
230
- }
231
- use(name) {
232
- return new ModelAccessor(name, this.http);
233
- }
234
- list() {
235
- return __async(this, arguments, function* (opts = {}) {
236
- const raw = yield this.http.get("/ontology/engine/runs", opts);
237
- return (0, import_core2.createPageResult)(
238
- asPagePayload(raw),
239
- (cursor) => this.list(__spreadProps(__spreadValues({}, opts), { cursor }))
162
+ var docsUrlSchema = import_zod.z.string().url().refine((url) => /^https?:\/\//.test(url), {
163
+ message: "docs must be an http or https URL"
164
+ });
165
+ var errorResponseSchema = import_zod.z.object({
166
+ code: import_zod.z.string().min(1).describe("Error code"),
167
+ message: import_zod.z.string().min(1).describe("Error message"),
168
+ requestId: import_zod.z.string().min(1).describe("Request ID"),
169
+ docs: docsUrlSchema.optional().describe("Documentation URL"),
170
+ fields: import_zod.z.array(errorFieldSchema).optional().describe("Array of error fields")
171
+ }).strict();
172
+ var retryStatusCodeSchema = import_zod.z.number().int().refine((status) => status === 429 || status >= 500 && status <= 599, {
173
+ message: "Retry status codes must be 429 or 5xx"
174
+ });
175
+ var retryConfigSchema = import_zod.z.object({
176
+ maxAttempts: import_zod.z.number().int().positive().default(3),
177
+ baseDelay: import_zod.z.number().int().positive().default(1e3),
178
+ strategy: import_zod.z.enum(BACKOFF_STRATEGIES).default("exponential"),
179
+ on: import_zod.z.array(retryStatusCodeSchema).default(DEFAULT_RETRY_ON),
180
+ jitter: import_zod.z.boolean().default(true)
181
+ }).strict().default({
182
+ maxAttempts: 3,
183
+ baseDelay: 1e3,
184
+ strategy: "exponential",
185
+ on: DEFAULT_RETRY_ON,
186
+ jitter: true
187
+ });
188
+ var numericValueSchema = import_zod.z.union([
189
+ import_zod.z.number(),
190
+ import_zod.z.literal(Number.POSITIVE_INFINITY),
191
+ import_zod.z.literal(Number.NEGATIVE_INFINITY)
192
+ ]);
193
+ var arrayFilterValueSchema = import_zod.z.union([
194
+ import_zod.z.array(import_zod.z.string()),
195
+ import_zod.z.array(numericValueSchema)
196
+ ]);
197
+ var scalarFilterValueSchema = import_zod.z.union([
198
+ import_zod.z.string(),
199
+ numericValueSchema,
200
+ import_zod.z.boolean(),
201
+ import_zod.z.date(),
202
+ import_zod.z.null(),
203
+ arrayFilterValueSchema
204
+ ]);
205
+ var comparableValueSchema = import_zod.z.union([numericValueSchema, import_zod.z.date()]);
206
+ var filterOperatorSchema = import_zod.z.object({
207
+ eq: scalarFilterValueSchema.optional(),
208
+ ne: scalarFilterValueSchema.optional(),
209
+ gt: comparableValueSchema.optional(),
210
+ gte: comparableValueSchema.optional(),
211
+ lt: comparableValueSchema.optional(),
212
+ lte: comparableValueSchema.optional(),
213
+ in: arrayFilterValueSchema.optional(),
214
+ nin: arrayFilterValueSchema.optional(),
215
+ contains: import_zod.z.string().optional(),
216
+ startsWith: import_zod.z.string().optional(),
217
+ endsWith: import_zod.z.string().optional()
218
+ }).strict().refine(
219
+ (value) => Object.values(value).some((entry) => entry !== void 0),
220
+ {
221
+ message: "At least one filter operator is required"
222
+ }
223
+ );
224
+ var filterValueSchema = import_zod.z.union([
225
+ scalarFilterValueSchema,
226
+ filterOperatorSchema
227
+ ]);
228
+ var filterConditionsSchema = import_zod.z.record(import_zod.z.string(), filterValueSchema);
229
+ var pageResultSchema = import_zod.z.object({
230
+ data: import_zod.z.array(import_zod.z.unknown()),
231
+ meta: responseMetaSchema.optional(),
232
+ pagination: paginationMetaSchema
233
+ }).strict();
234
+ var FrontalError = class extends Error {
235
+ code;
236
+ requestId;
237
+ statusCode;
238
+ docs;
239
+ rateLimit;
240
+ /**
241
+ * @param response - The parsed error response from the API.
242
+ * @param statusCode - The HTTP status code.
243
+ * @param rateLimit - Optional rate-limit headers from the response.
244
+ */
245
+ constructor(response, statusCode, rateLimit) {
246
+ super(response.message);
247
+ this.name = "FrontalError";
248
+ this.code = response.code;
249
+ this.requestId = response.requestId;
250
+ this.statusCode = statusCode;
251
+ this.docs = response.docs;
252
+ this.rateLimit = rateLimit;
253
+ Object.setPrototypeOf(this, new.target.prototype);
254
+ if (Error.captureStackTrace) {
255
+ Error.captureStackTrace(this);
256
+ }
257
+ }
258
+ };
259
+ var NotFoundError = class extends FrontalError {
260
+ constructor(r, rateLimit) {
261
+ super(r, 404, rateLimit);
262
+ this.name = "NotFoundError";
263
+ }
264
+ };
265
+ var UnauthorizedError = class extends FrontalError {
266
+ constructor(r, rateLimit) {
267
+ super(r, 401, rateLimit);
268
+ this.name = "UnauthorizedError";
269
+ }
270
+ };
271
+ var ForbiddenError = class extends FrontalError {
272
+ constructor(r, rateLimit) {
273
+ super(r, 403, rateLimit);
274
+ this.name = "ForbiddenError";
275
+ }
276
+ };
277
+ var ValidationError = class extends FrontalError {
278
+ /** Per-field validation errors returned by the API. */
279
+ fields;
280
+ constructor(r, rateLimit) {
281
+ super(r, 400, rateLimit);
282
+ this.name = "ValidationError";
283
+ this.fields = r.fields ?? [];
284
+ }
285
+ };
286
+ var ConflictError = class extends FrontalError {
287
+ constructor(r, rateLimit) {
288
+ super(r, 409, rateLimit);
289
+ this.name = "ConflictError";
290
+ }
291
+ };
292
+ var RateLimitError = class extends FrontalError {
293
+ /** Recommended delay in seconds before retrying. */
294
+ retryAfter;
295
+ constructor(r, retryAfter, rateLimit) {
296
+ super(r, 429, rateLimit);
297
+ this.name = "RateLimitError";
298
+ this.retryAfter = retryAfter;
299
+ }
300
+ };
301
+ var ServiceError = class extends FrontalError {
302
+ constructor(r, status, rateLimit) {
303
+ super(r, status, rateLimit);
304
+ this.name = "ServiceError";
305
+ }
306
+ };
307
+ var NetworkError = class extends Error {
308
+ constructor(cause) {
309
+ super("Network error \u2014 could not reach Frontal API");
310
+ this.cause = cause;
311
+ this.name = "NetworkError";
312
+ Object.setPrototypeOf(this, new.target.prototype);
313
+ if (Error.captureStackTrace) {
314
+ Error.captureStackTrace(this, new.target);
315
+ }
316
+ }
317
+ };
318
+ function normalizeErrorBody(body) {
319
+ const parsed = errorResponseSchema.safeParse(body);
320
+ if (parsed.success) return parsed.data;
321
+ const fallback = typeof body === "object" && body !== null ? body : {};
322
+ const code = typeof fallback.code === "string" && fallback.code.length > 0 ? fallback.code : "UNKNOWN_ERROR";
323
+ const hasExplicitCode = typeof fallback.code === "string" && fallback.code.length > 0;
324
+ const message = hasExplicitCode && typeof fallback.message === "string" && fallback.message.length > 0 ? fallback.message : "An unknown error occurred";
325
+ return {
326
+ code,
327
+ message,
328
+ requestId: typeof fallback.requestId === "string" && fallback.requestId.length > 0 ? fallback.requestId : "unknown",
329
+ docs: typeof fallback.docs === "string" ? fallback.docs : void 0,
330
+ fields: Array.isArray(fallback.fields) ? fallback.fields : void 0
331
+ };
332
+ }
333
+ function parseFrontalError(body, status, retryAfter, rateLimit) {
334
+ const normalized = normalizeErrorBody(body);
335
+ switch (status) {
336
+ case 400:
337
+ return new ValidationError(normalized, rateLimit);
338
+ case 401:
339
+ return new UnauthorizedError(normalized, rateLimit);
340
+ case 403:
341
+ return new ForbiddenError(normalized, rateLimit);
342
+ case 404:
343
+ return new NotFoundError(normalized, rateLimit);
344
+ case 409:
345
+ return new ConflictError(normalized, rateLimit);
346
+ case 429: {
347
+ const parsedRetry = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;
348
+ return new RateLimitError(
349
+ normalized,
350
+ Number.isFinite(parsedRetry) ? parsedRetry : 60,
351
+ rateLimit
240
352
  );
241
- });
353
+ }
354
+ default:
355
+ return new ServiceError(normalized, status, rateLimit);
242
356
  }
243
- create(definition) {
244
- return __async(this, null, function* () {
245
- const body = ModelDefinitionSchema.parse(definition);
246
- return this.http.post("/ontology/engine/runs", body);
247
- });
357
+ }
358
+ var CircuitBreaker = class {
359
+ failures = 0;
360
+ lastFailureTime = 0;
361
+ state = "CLOSED";
362
+ config;
363
+ constructor(config) {
364
+ this.config = config;
248
365
  }
249
- validate(definition) {
250
- return __async(this, null, function* () {
251
- const body = ModelDefinitionSchema.parse(definition);
252
- return this.http.post("/ontology/engine/ontologies/validate", body);
253
- });
366
+ /** Returns the current circuit state. */
367
+ getState() {
368
+ return this.state;
254
369
  }
255
- checkIntegrity() {
256
- return __async(this, null, function* () {
257
- return this.http.get("/ontology/engine/health");
258
- });
370
+ /** Returns the current consecutive failure count. */
371
+ getFailures() {
372
+ return this.failures;
373
+ }
374
+ reset() {
375
+ this.failures = 0;
376
+ this.state = "CLOSED";
377
+ this.config.onClose?.();
378
+ }
379
+ /**
380
+ * Executes an async function through the circuit breaker.
381
+ * Throws CircuitBreakerOpenError immediately if the circuit is OPEN
382
+ * and the reset timeout has not elapsed. On success in HALF_OPEN state,
383
+ * resets the circuit to CLOSED.
384
+ *
385
+ * @param fn - The async operation to protect.
386
+ * @throws {CircuitBreakerOpenError} If the circuit is OPEN.
387
+ */
388
+ async execute(fn) {
389
+ if (this.state === "OPEN") {
390
+ if (Date.now() - this.lastFailureTime > this.config.resetTimeoutMs) {
391
+ this.state = "HALF_OPEN";
392
+ this.config.onHalfOpen?.();
393
+ } else {
394
+ throw new CircuitBreakerOpenError(
395
+ this.config.resetTimeoutMs - (Date.now() - this.lastFailureTime)
396
+ );
397
+ }
398
+ }
399
+ try {
400
+ const result = await fn();
401
+ if (this.state === "HALF_OPEN") {
402
+ this.reset();
403
+ }
404
+ return result;
405
+ } catch (error) {
406
+ this.failures++;
407
+ this.lastFailureTime = Date.now();
408
+ if (this.failures >= this.config.failureThreshold) {
409
+ this.state = "OPEN";
410
+ this.config.onOpen?.();
411
+ }
412
+ throw error;
413
+ }
414
+ }
415
+ /** Manually forces the circuit into the OPEN state. */
416
+ forceOpen() {
417
+ this.state = "OPEN";
418
+ this.lastFailureTime = Date.now();
419
+ }
420
+ /** Manually resets the circuit to the CLOSED state. */
421
+ forceClose() {
422
+ this.reset();
259
423
  }
260
424
  };
261
- var ModelAccessor = class {
262
- constructor(_name, http) {
263
- this._name = _name;
264
- this.http = http;
425
+ var CircuitBreakerOpenError = class extends Error {
426
+ /** Milliseconds remaining until the circuit transitions to HALF_OPEN. */
427
+ retryAfterMs;
428
+ constructor(retryAfterMs) {
429
+ super(
430
+ `Circuit breaker is open \u2014 retry after ${Math.ceil(retryAfterMs / 1e3)}s`
431
+ );
432
+ this.name = "CircuitBreakerOpenError";
433
+ this.retryAfterMs = retryAfterMs;
434
+ Object.setPrototypeOf(this, new.target.prototype);
265
435
  }
266
- get(version) {
267
- return __async(this, null, function* () {
268
- const params = version ? { version } : void 0;
269
- return this.http.get("/ontology/engine/runs", params);
270
- });
436
+ };
437
+ function computeBaseDelay(attempt, strategy, baseDelay) {
438
+ const normalizedAttempt = Math.floor(attempt);
439
+ switch (strategy) {
440
+ case "linear":
441
+ return Math.max(0, baseDelay * (normalizedAttempt + 1));
442
+ case "constant":
443
+ return baseDelay;
444
+ default:
445
+ return baseDelay * EXPONENTIAL_BASE ** normalizedAttempt;
271
446
  }
272
- update(definition) {
273
- return __async(this, null, function* () {
274
- return this.http.post("/ontology/engine/runs", definition);
275
- });
447
+ }
448
+ function calculateDelay(attempt, strategyOrConfig, baseDelay, withJitter = false) {
449
+ if (typeof strategyOrConfig === "object") {
450
+ const strategy = "strategy" in strategyOrConfig ? strategyOrConfig.strategy : strategyOrConfig.backoff;
451
+ const delayBase = "baseDelay" in strategyOrConfig ? strategyOrConfig.baseDelay : strategyOrConfig.retryDelay;
452
+ const delay2 = computeBaseDelay(attempt, strategy, delayBase);
453
+ const shouldJitter = "jitter" in strategyOrConfig ? Boolean(strategyOrConfig.jitter) : true;
454
+ if (!shouldJitter) return delay2;
455
+ return delay2 + Math.random() * (JITTER_MAX / 2);
456
+ }
457
+ const delay = computeBaseDelay(
458
+ attempt,
459
+ strategyOrConfig,
460
+ Math.max(0, baseDelay ?? 0)
461
+ );
462
+ if (!withJitter) return delay;
463
+ return delay + Math.random() * (JITTER_MAX / 2);
464
+ }
465
+ function snakeToCamel(str) {
466
+ const prefix = str.match(/^_+/)?.[0] ?? "";
467
+ const body = str.slice(prefix.length);
468
+ if (!body) return str;
469
+ return prefix + body.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
470
+ }
471
+ function camelToSnake(str) {
472
+ return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
473
+ }
474
+ var NEVER_TRANSFORM_KEYS = /* @__PURE__ */ new Set(["$ref", "$schema", "$id"]);
475
+ function isStream(obj) {
476
+ return typeof obj === "object" && obj !== null && (typeof obj.pipe === "function" || typeof obj.getReader === "function");
477
+ }
478
+ function deepTransformKeys(obj, transform, skipKeys) {
479
+ if (obj === null || obj === void 0) return obj;
480
+ if (typeof obj !== "object") return obj;
481
+ if (obj instanceof Date || typeof Buffer !== "undefined" && obj instanceof Buffer || obj instanceof RegExp || obj instanceof FormData || obj instanceof File || obj instanceof Blob)
482
+ return obj;
483
+ if (isStream(obj)) return obj;
484
+ if (Array.isArray(obj)) {
485
+ return obj.map(
486
+ (item) => deepTransformKeys(item, transform, skipKeys)
487
+ );
276
488
  }
277
- delete(force = false) {
278
- return __async(this, null, function* () {
279
- return this.http.post("/ontology/engine/runs", {
280
- action: "delete-model",
281
- force
489
+ const proto = Object.getPrototypeOf(obj);
490
+ if (proto !== Object.prototype && proto !== null) return obj;
491
+ const result = {};
492
+ for (const key of Object.keys(obj)) {
493
+ const shouldSkip = skipKeys?.has(key) || NEVER_TRANSFORM_KEYS.has(key);
494
+ const newKey = shouldSkip ? key : transform(key);
495
+ result[newKey] = deepTransformKeys(
496
+ obj[key],
497
+ transform,
498
+ skipKeys
499
+ );
500
+ }
501
+ return result;
502
+ }
503
+ function deepCamelToSnake(obj, skipKeys) {
504
+ return deepTransformKeys(obj, camelToSnake, skipKeys);
505
+ }
506
+ function deepSnakeToCamel(obj, skipKeys) {
507
+ return deepTransformKeys(obj, snakeToCamel, skipKeys);
508
+ }
509
+ var HttpClient = class {
510
+ constructor(config) {
511
+ this.config = config;
512
+ if (config.circuitBreaker) {
513
+ this.breaker = new CircuitBreaker({
514
+ failureThreshold: config.circuitBreaker.failureThreshold,
515
+ resetTimeoutMs: config.circuitBreaker.resetTimeoutMs
282
516
  });
517
+ }
518
+ }
519
+ breaker;
520
+ /**
521
+ * Sends a GET request.
522
+ * @param path - API endpoint path.
523
+ * @param params - Optional query parameters.
524
+ * @param schema - Optional Zod schema for response validation.
525
+ */
526
+ async get(path, params, schema) {
527
+ return this.request("GET", path, void 0, params, schema);
528
+ }
529
+ /**
530
+ * Sends a POST request with a JSON body.
531
+ * @param path - API endpoint path.
532
+ * @param body - Request payload (converted to snake_case automatically).
533
+ * @param schema - Optional Zod schema for response validation.
534
+ */
535
+ async post(path, body, schema) {
536
+ return this.request("POST", path, body ?? {}, void 0, schema);
537
+ }
538
+ /**
539
+ * Sends a PUT request with a JSON body.
540
+ * @param path - API endpoint path.
541
+ * @param body - Request payload (converted to snake_case automatically).
542
+ * @param schema - Optional Zod schema for response validation.
543
+ */
544
+ async put(path, body, schema) {
545
+ return this.request("PUT", path, body ?? {}, void 0, schema);
546
+ }
547
+ /**
548
+ * Sends a PATCH request with a JSON body.
549
+ * @param path - API endpoint path.
550
+ * @param body - Request payload (converted to snake_case automatically).
551
+ * @param schema - Optional Zod schema for response validation.
552
+ */
553
+ async patch(path, body, schema) {
554
+ return this.request("PATCH", path, body ?? {}, void 0, schema);
555
+ }
556
+ /**
557
+ * Sends a DELETE request.
558
+ * @param path - API endpoint path.
559
+ * @param params - Optional query parameters.
560
+ * @param schema - Optional Zod schema for response validation.
561
+ */
562
+ async delete(path, params, schema) {
563
+ return this.request("DELETE", path, {}, params, schema);
564
+ }
565
+ /**
566
+ * Sends a raw PUT request with a binary/stream body.
567
+ * @param path - API endpoint path.
568
+ * @param body - Binary buffer or readable stream.
569
+ * @param contentType - MIME type of the body.
570
+ * @param headers - Additional request headers.
571
+ * @returns The parsed JSON response with keys converted to camelCase.
572
+ */
573
+ async putRaw(path, body, contentType, headers = {}) {
574
+ const url = this.buildUrl(path);
575
+ const res = await this.fetchWithTimeout(url, {
576
+ method: "PUT",
577
+ headers: this.buildHeaders({ "Content-Type": contentType, ...headers }),
578
+ body
283
579
  });
580
+ if (!res.ok) await this.throwError(res);
581
+ if (res.status === 204) return void 0;
582
+ const json = await res.json();
583
+ return typeof json === "object" && json !== null ? deepSnakeToCamel(json) : json;
284
584
  }
285
- relationships() {
286
- return __async(this, null, function* () {
287
- return this.http.get("/ontology/engine/runs");
585
+ /**
586
+ * Opens a GET SSE stream, yielding parsed server-sent events.
587
+ * @param path - API endpoint path.
588
+ * @param params - Optional query parameters.
589
+ * @yields SSE event objects with `type`, `data`, and optional `id` fields.
590
+ */
591
+ async *stream(path, params) {
592
+ const url = this.buildUrl(path, params);
593
+ const res = await this.fetchWithTimeout(url, {
594
+ method: "GET",
595
+ headers: this.buildHeaders({ Accept: "text/event-stream" })
288
596
  });
597
+ if (!res.ok) await this.throwError(res);
598
+ yield* this.parseSSEResponse(res);
289
599
  }
290
- addRelationship(definition) {
291
- return __async(this, null, function* () {
292
- const body = RelationshipDefinitionSchema.parse(definition);
293
- return this.http.post("/ontology/engine/runs", body);
600
+ /**
601
+ * Sends a POST request that returns an SSE stream.
602
+ * @param path - API endpoint path.
603
+ * @param body - Request payload (converted to snake_case automatically).
604
+ * @yields SSE event objects with `type`, `data`, and optional `id` fields.
605
+ */
606
+ async *postStream(path, body) {
607
+ const url = this.buildUrl(path);
608
+ const res = await this.fetchWithTimeout(url, {
609
+ method: "POST",
610
+ headers: this.buildHeaders({ Accept: "text/event-stream" }),
611
+ body: JSON.stringify(body ?? {})
294
612
  });
613
+ if (!res.ok) await this.throwError(res);
614
+ yield* this.parseSSEResponse(res);
295
615
  }
296
- removeRelationship(relationshipId) {
297
- return __async(this, null, function* () {
298
- return this.http.post("/ontology/engine/runs", {
299
- action: "delete-relationship",
300
- relationshipId
301
- });
616
+ /**
617
+ * Sends a POST request and returns the raw Response object.
618
+ * @param path - API endpoint path.
619
+ * @param body - Request payload.
620
+ * @param headers - Additional request headers.
621
+ * @returns The raw fetch Response (caller must handle parsing).
622
+ */
623
+ async postRaw(path, body, headers = {}) {
624
+ const url = this.buildUrl(path);
625
+ const res = await this.fetchWithTimeout(url, {
626
+ method: "POST",
627
+ headers: new Headers(this.buildHeaders(headers)),
628
+ body: JSON.stringify(body ?? {})
302
629
  });
630
+ if (!res.ok) await this.throwError(res);
631
+ return res;
303
632
  }
304
- validateData() {
305
- return __async(this, null, function* () {
306
- return this.http.post("/ontology/engine/ontologies/validate");
633
+ /**
634
+ * Sends a POST request with a FormData body (multipart/form-data).
635
+ * Automatically removes the Content-Type header so the browser sets the
636
+ * correct multipart boundary.
637
+ * @param path - API endpoint path.
638
+ * @param formData - FormData payload.
639
+ * @param headers - Additional request headers.
640
+ * @returns The parsed JSON response with keys converted to camelCase.
641
+ */
642
+ async postFormData(path, formData, headers = {}) {
643
+ const url = this.buildUrl(path);
644
+ const merged = new Headers(this.buildHeaders(headers));
645
+ merged.delete("Content-Type");
646
+ const res = await this.fetchWithTimeout(url, {
647
+ method: "POST",
648
+ headers: merged,
649
+ body: formData
307
650
  });
651
+ if (!res.ok) await this.throwError(res);
652
+ const json = await res.json();
653
+ return deepSnakeToCamel(json);
308
654
  }
309
- versions() {
310
- return __async(this, null, function* () {
311
- return this.http.get("/ontology/engine/runs");
655
+ /**
656
+ * Sends a raw GET request and returns the Response object directly.
657
+ * @param path - API endpoint path.
658
+ * @param params - Optional query parameters.
659
+ * @param headers - Additional request headers.
660
+ * @returns The raw fetch Response (caller must handle parsing).
661
+ */
662
+ async getRaw(path, params, headers = {}) {
663
+ const url = this.buildUrl(path, params);
664
+ const res = await this.fetchWithTimeout(url, {
665
+ method: "GET",
666
+ headers: this.buildHeaders(headers)
312
667
  });
668
+ if (!res.ok) await this.throwError(res);
669
+ return res;
670
+ }
671
+ async *parseSSEResponse(res) {
672
+ if (!res.body) return;
673
+ const reader = res.body.getReader();
674
+ const decoder = new TextDecoder();
675
+ let buffer = "";
676
+ while (true) {
677
+ const { done, value } = await reader.read();
678
+ if (done) break;
679
+ buffer += decoder.decode(value, { stream: true });
680
+ const lines = buffer.split("\n");
681
+ buffer = lines.pop() ?? "";
682
+ let event = {
683
+ type: "message",
684
+ data: null
685
+ };
686
+ for (const rawLine of lines) {
687
+ const line = rawLine.trimEnd();
688
+ if (line.startsWith("id:")) {
689
+ event.id = line.slice(3).trim();
690
+ } else if (line.startsWith("event:")) {
691
+ event.type = line.slice(6).trim();
692
+ } else if (line.startsWith("data:")) {
693
+ const payload = line.slice(5).trim();
694
+ try {
695
+ const parsed = JSON.parse(payload);
696
+ event.data = typeof parsed === "object" && parsed !== null ? deepSnakeToCamel(parsed) : parsed;
697
+ } catch {
698
+ event.data = payload;
699
+ }
700
+ } else if (line === "") {
701
+ if (event.data !== null) yield event;
702
+ event = { type: "message", data: null };
703
+ }
704
+ }
705
+ }
706
+ }
707
+ async request(method, path, body, params, schema, attempt = 0) {
708
+ const url = this.buildUrl(path, params);
709
+ const requestId = crypto.randomUUID();
710
+ const transformedBody = body !== void 0 && body !== null ? deepCamelToSnake(body) : body;
711
+ const reqInit = {
712
+ method,
713
+ headers: this.buildHeaders({ "X-Request-Id": requestId }),
714
+ ...method !== "GET" ? { body: JSON.stringify(transformedBody ?? {}) } : { body: void 0 }
715
+ };
716
+ this.config.logger?.request?.(method, url, reqInit);
717
+ const executeRequest = async () => {
718
+ try {
719
+ return await this.fetchWithTimeout(url, reqInit);
720
+ } catch (error) {
721
+ this.config.logger?.error?.(error);
722
+ throw new NetworkError(error);
723
+ }
724
+ };
725
+ let res;
726
+ try {
727
+ res = this.breaker ? await this.breaker.execute(executeRequest) : await executeRequest();
728
+ } catch (error) {
729
+ if (error instanceof CircuitBreakerOpenError) {
730
+ throw new Error(
731
+ `Circuit breaker is open. Retry after ${Math.ceil(error.retryAfterMs / 1e3)}s.`
732
+ );
733
+ }
734
+ throw error;
735
+ }
736
+ this.config.logger?.response?.(res);
737
+ if (!res.ok) {
738
+ const shouldRetry = [429, 500, 502, 503, 504].includes(res.status) && attempt < this.config.maxRetries;
739
+ if (shouldRetry) {
740
+ const retryAfterValue = res.headers.get("Retry-After");
741
+ const retryAfterSeconds = retryAfterValue ? Number.parseInt(retryAfterValue, 10) : Number.NaN;
742
+ const delay = Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1e3 : calculateDelay(
743
+ attempt,
744
+ "exponential",
745
+ this.config.retryDelay,
746
+ true
747
+ );
748
+ await sleep(delay);
749
+ return this.request(method, path, body, params, schema, attempt + 1);
750
+ }
751
+ await this.throwError(res);
752
+ }
753
+ if (res.status === 204) return void 0;
754
+ const contentType = (res.headers.get("content-type") || "").toLowerCase();
755
+ const payload = contentType.includes("application/json") ? await res.json() : await res.text();
756
+ const transformedPayload = typeof payload === "object" && payload !== null ? deepSnakeToCamel(payload) : payload;
757
+ if (schema) {
758
+ try {
759
+ const parsed = schema.safeParse(transformedPayload);
760
+ if (!parsed.success) {
761
+ this.config.logger?.error?.(parsed.error);
762
+ throw parsed.error;
763
+ }
764
+ return parsed.data;
765
+ } catch (error) {
766
+ if (error instanceof Error && error.message.includes("_zod")) {
767
+ return transformedPayload;
768
+ }
769
+ throw error;
770
+ }
771
+ }
772
+ return transformedPayload;
773
+ }
774
+ parseRateLimit(res) {
775
+ const limit = res.headers.get("X-RateLimit-Limit");
776
+ const remaining = res.headers.get("X-RateLimit-Remaining");
777
+ const reset = res.headers.get("X-RateLimit-Reset");
778
+ if (limit && remaining && reset) {
779
+ return {
780
+ limit: Number.parseInt(limit, 10),
781
+ remaining: Number.parseInt(remaining, 10),
782
+ reset: Number.parseInt(reset, 10)
783
+ };
784
+ }
785
+ return void 0;
786
+ }
787
+ async throwError(res) {
788
+ let body;
789
+ try {
790
+ body = await res.json();
791
+ } catch {
792
+ body = {};
793
+ }
794
+ const retryAfter = res.headers.get("Retry-After") ?? void 0;
795
+ const rateLimit = this.parseRateLimit(res);
796
+ throw parseFrontalError(body, res.status, retryAfter, rateLimit);
797
+ }
798
+ buildUrl(path, params) {
799
+ const base = this.config.baseUrl.replace(/\/$/, "");
800
+ let normalizedPath = path.startsWith("/") ? path : `/${path}`;
801
+ if (base.endsWith("/v1") && normalizedPath.startsWith("/v1/")) {
802
+ if (this.config.debug) {
803
+ console.warn(
804
+ `[SDK] Double /v1/ prefix detected and normalized. The base URL already includes "/v1" but the route "${normalizedPath}" also starts with "/v1/". Write routes without a leading "/v1".`
805
+ );
806
+ }
807
+ normalizedPath = normalizedPath.slice("/v1".length);
808
+ }
809
+ const url = `${base}${normalizedPath}`;
810
+ const transformedParams = params ? deepCamelToSnake(params) : params;
811
+ if (!transformedParams || Object.keys(transformedParams).length === 0) {
812
+ return url;
813
+ }
814
+ const query = Object.entries(transformedParams).filter(([, value]) => value !== void 0 && value !== null).map(
815
+ ([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
816
+ ).join("&");
817
+ return query ? `${url}?${query}` : url;
818
+ }
819
+ buildHeaders(extra = {}) {
820
+ return {
821
+ // The opaque API key (`frt_…`) is the sole public credential. The platform
822
+ // edge validates it and exchanges it for a short-lived JWT before reaching
823
+ // any service — the SDK never sees or sends a JWT.
824
+ Authorization: `Bearer ${this.config.apiKey}`,
825
+ "Content-Type": "application/json",
826
+ Accept: "application/json",
827
+ "User-Agent": "@frontal-labs/core",
828
+ "X-Frontal-Core": `typescript@${SDK_VERSION}`,
829
+ "X-Frontal-Environment": this.config.environment,
830
+ ...this.config.headers,
831
+ ...extra
832
+ };
833
+ }
834
+ async fetchWithTimeout(url, init) {
835
+ const controller = new AbortController();
836
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
837
+ try {
838
+ return await (this.config.fetch ?? fetch)(url, {
839
+ ...init,
840
+ signal: controller.signal
841
+ });
842
+ } finally {
843
+ clearTimeout(timer);
844
+ }
313
845
  }
314
846
  };
315
- var MigrationsNamespace = class {
316
- constructor(http) {
317
- this.http = http;
847
+ var sleep = async (ms) => new Promise((resolve) => {
848
+ setTimeout(resolve, ms);
849
+ });
850
+ var apiKeySchema = import_zod2.z.string().min(9, "FRONTAL_API_KEY must be at least 9 characters").max(128, "FRONTAL_API_KEY must be at most 128 characters").refine(
851
+ (val) => /^frt_[A-Za-z0-9_]+$/.test(val) || /^fr_typed[A-Za-z0-9_]+$/.test(val),
852
+ "FRONTAL_API_KEY must start with frt_"
853
+ );
854
+ var debugSchema = import_zod2.z.union([
855
+ import_zod2.z.literal("true"),
856
+ import_zod2.z.literal("false"),
857
+ import_zod2.z.literal("1"),
858
+ import_zod2.z.literal("0")
859
+ ]).optional().default("false").transform((val) => val === "true" || val === "1");
860
+ var env = createEnv({
861
+ server: {
862
+ FRONTAL_ENV: import_zod2.z.enum(["development", "test", "production"]).default("development"),
863
+ FRONTAL_API_KEY: apiKeySchema.optional(),
864
+ FRONTAL_API_URL: import_zod2.z.url("FRONTAL_API_URL must be a valid URL").optional(),
865
+ FRONTAL_DEBUG: debugSchema
866
+ },
867
+ runtimeEnv: {
868
+ FRONTAL_ENV: process.env.FRONTAL_ENV,
869
+ FRONTAL_API_KEY: process.env.FRONTAL_API_KEY,
870
+ FRONTAL_API_URL: process.env.FRONTAL_API_URL,
871
+ FRONTAL_DEBUG: process.env.FRONTAL_DEBUG
872
+ },
873
+ emptyStringAsUndefined: true
874
+ });
875
+ var unwrapClientError = (error) => {
876
+ if (error instanceof NetworkError) {
877
+ if (error.cause instanceof Error) {
878
+ throw error.cause;
879
+ }
880
+ throw new Error(String(error.cause));
318
881
  }
319
- plan(request) {
320
- return __async(this, null, function* () {
321
- return this.http.post(
322
- "/ontology/engine/ontologies/compare-versions",
323
- request
324
- );
882
+ throw error;
883
+ };
884
+ var FrontalClient = class {
885
+ config;
886
+ _http;
887
+ /**
888
+ * @param config - Validated client configuration output from clientConfigSchema.
889
+ */
890
+ constructor(config) {
891
+ Object.defineProperty(this, "config", {
892
+ value: config,
893
+ writable: false,
894
+ enumerable: true
325
895
  });
326
- }
327
- apply(planId, strategy = "zero-downtime") {
328
- return __async(this, null, function* () {
329
- return this.http.post("/ontology/engine/runs", { planId, strategy });
896
+ const http = new HttpClient(config);
897
+ Object.defineProperty(this, "_http", {
898
+ value: http,
899
+ writable: false,
900
+ enumerable: true
330
901
  });
331
- }
332
- rollback(_migrationId) {
333
- return __async(this, null, function* () {
334
- return this.http.post("/ontology/engine/runs");
902
+ Object.defineProperty(this, "httpClient", {
903
+ get() {
904
+ return http;
905
+ },
906
+ enumerable: true
335
907
  });
336
908
  }
337
- history() {
338
- return __async(this, arguments, function* (opts = {}) {
339
- const raw = yield this.http.get("/ontology/engine/runs", opts);
340
- return (0, import_core2.createPageResult)(
341
- asPagePayload(raw),
342
- (cursor) => this.history(__spreadProps(__spreadValues({}, opts), { cursor }))
343
- );
344
- });
909
+ /** Public accessor for the underlying HttpClient. */
910
+ get httpClient() {
911
+ return this._http;
912
+ }
913
+ /**
914
+ * Sends a GET request and optionally validates the response against a schema.
915
+ * @param path - API endpoint path.
916
+ * @param schema - Optional Zod schema for response validation.
917
+ */
918
+ async get(path, schema) {
919
+ try {
920
+ return await this._http.get(path, void 0, schema);
921
+ } catch (error) {
922
+ throw unwrapClientError(error);
923
+ }
924
+ }
925
+ /**
926
+ * Sends a POST request with an optional JSON body and response schema.
927
+ * @param path - API endpoint path.
928
+ * @param body - Request payload (converted to snake_case automatically).
929
+ * @param schema - Optional Zod schema for response validation.
930
+ */
931
+ async post(path, body, schema) {
932
+ try {
933
+ return await this._http.post(path, body, schema);
934
+ } catch (error) {
935
+ throw unwrapClientError(error);
936
+ }
937
+ }
938
+ /**
939
+ * Sends a PUT request with an optional JSON body and response schema.
940
+ * @param path - API endpoint path.
941
+ * @param body - Request payload (converted to snake_case automatically).
942
+ * @param schema - Optional Zod schema for response validation.
943
+ */
944
+ async put(path, body, schema) {
945
+ try {
946
+ return await this._http.put(path, body, schema);
947
+ } catch (error) {
948
+ throw unwrapClientError(error);
949
+ }
345
950
  }
951
+ /**
952
+ * Sends a PATCH request with an optional JSON body and response schema.
953
+ * @param path - API endpoint path.
954
+ * @param body - Request payload (converted to snake_case automatically).
955
+ * @param schema - Optional Zod schema for response validation.
956
+ */
957
+ async patch(path, body, schema) {
958
+ try {
959
+ return await this._http.patch(path, body, schema);
960
+ } catch (error) {
961
+ throw unwrapClientError(error);
962
+ }
963
+ }
964
+ /**
965
+ * Sends a DELETE request with optional query parameters and response schema.
966
+ * @param path - API endpoint path.
967
+ * @param params - Query parameters (converted to snake_case automatically).
968
+ * @param schema - Optional Zod schema for response validation.
969
+ */
970
+ async delete(path, params, schema) {
971
+ try {
972
+ return await this._http.delete(path, params, schema);
973
+ } catch (error) {
974
+ throw unwrapClientError(error);
975
+ }
976
+ }
977
+ /**
978
+ * Opens a GET SSE stream and yields parsed server-sent events.
979
+ * @param path - API endpoint path.
980
+ * @param params - Optional query parameters.
981
+ * @yields Objects with `type`, `data`, and optional `id` fields from SSE events.
982
+ */
983
+ async *stream(path, params) {
984
+ try {
985
+ yield* this._http.stream(path, params);
986
+ } catch (error) {
987
+ throw unwrapClientError(error);
988
+ }
989
+ }
990
+ /**
991
+ * Sends a raw PUT request with a binary/stream body and custom content type.
992
+ * @param path - API endpoint path.
993
+ * @param body - Binary buffer or readable stream to upload.
994
+ * @param contentType - MIME type of the body.
995
+ * @param headers - Additional request headers.
996
+ * @returns The parsed JSON response (keys converted to camelCase).
997
+ */
998
+ async putRaw(path, body, contentType, headers = {}) {
999
+ try {
1000
+ return await this._http.putRaw(path, body, contentType, headers);
1001
+ } catch (error) {
1002
+ throw unwrapClientError(error);
1003
+ }
1004
+ }
1005
+ };
1006
+ var getDefaultClient = () => {
1007
+ if (!env.FRONTAL_API_KEY) {
1008
+ throw new Error(
1009
+ "FRONTAL_API_KEY environment variable is required. Set it in your environment or pass apiKey explicitly to new FrontalClient()."
1010
+ );
1011
+ }
1012
+ return new FrontalClient({
1013
+ apiKey: env.FRONTAL_API_KEY,
1014
+ baseUrl: env.FRONTAL_API_URL ?? DEFAULT_BASE_URL,
1015
+ timeout: 3e4,
1016
+ maxRetries: 3,
1017
+ retryDelay: 1e3,
1018
+ headers: {},
1019
+ environment: env.FRONTAL_ENV,
1020
+ debug: env.FRONTAL_DEBUG
1021
+ });
346
1022
  };
347
- var RulesNamespace = class {
1023
+ var API_KEY_PATTERN = new RegExp(`^${API_KEY_PREFIX}[A-Za-z0-9_-]+$`);
1024
+ var loggerFnSchema = import_zod3.z.custom(
1025
+ (value) => typeof value === "function",
1026
+ "Expected function"
1027
+ );
1028
+ var headersSchema = import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).superRefine((headers, ctx) => {
1029
+ for (const key of Object.keys(headers)) {
1030
+ if (key.trim().length === 0) {
1031
+ ctx.addIssue({
1032
+ code: import_zod3.z.ZodIssueCode.custom,
1033
+ message: "Header names must be non-empty",
1034
+ path: []
1035
+ });
1036
+ return;
1037
+ }
1038
+ }
1039
+ }).default({});
1040
+ var clientConfigSchema = import_zod3.z.object({
1041
+ apiKey: import_zod3.z.string().min(9, "apiKey is required").regex(API_KEY_PATTERN, `apiKey must start with "${API_KEY_PREFIX}"`),
1042
+ baseUrl: import_zod3.z.string().url().refine(
1043
+ (value) => value.startsWith("https://") || value.startsWith("http://"),
1044
+ {
1045
+ message: "baseUrl must use http or https"
1046
+ }
1047
+ ).default(DEFAULT_BASE_URL),
1048
+ timeout: import_zod3.z.number().int().positive().default(3e4),
1049
+ maxRetries: import_zod3.z.number().int().min(0).max(10).default(3),
1050
+ retryDelay: import_zod3.z.number().int().positive().default(1e3),
1051
+ headers: headersSchema,
1052
+ environment: import_zod3.z.string().default("production"),
1053
+ debug: import_zod3.z.boolean().default(false),
1054
+ fetch: import_zod3.z.custom((value) => typeof value === "function").optional(),
1055
+ logger: import_zod3.z.object({
1056
+ request: loggerFnSchema.optional(),
1057
+ response: loggerFnSchema.optional(),
1058
+ error: loggerFnSchema.optional()
1059
+ }).optional(),
1060
+ circuitBreaker: import_zod3.z.object({
1061
+ failureThreshold: import_zod3.z.number().int().positive().default(5),
1062
+ resetTimeoutMs: import_zod3.z.number().int().positive().default(3e4)
1063
+ }).optional()
1064
+ }).strict();
1065
+ function asPagePayload(raw) {
1066
+ return raw;
1067
+ }
1068
+ var paginationSchema = import_zod4.z.object({
1069
+ cursor: import_zod4.z.string().min(1),
1070
+ hasMore: import_zod4.z.boolean(),
1071
+ total: import_zod4.z.number().int().min(0).optional(),
1072
+ limit: import_zod4.z.number().int().positive().optional(),
1073
+ offset: import_zod4.z.number().int().min(0).optional()
1074
+ }).strict();
1075
+ function buildPageResult(data, pagination, fetchNext, meta) {
1076
+ let nextPagePromise = null;
1077
+ const page = {
1078
+ data,
1079
+ meta,
1080
+ pagination,
1081
+ _fetchNextPage: fetchNext,
1082
+ async nextPage() {
1083
+ if (!this.pagination.hasMore) return null;
1084
+ if (!nextPagePromise) {
1085
+ nextPagePromise = (async () => {
1086
+ let result = await this._fetchNextPage();
1087
+ if (!result && this._fallbackFetchNextPage) {
1088
+ result = await this._fallbackFetchNextPage();
1089
+ }
1090
+ if (result) {
1091
+ const mutableResult = result;
1092
+ mutableResult._fallbackFetchNextPage = this._fallbackFetchNextPage ?? this._fetchNextPage;
1093
+ }
1094
+ return result;
1095
+ })().finally(() => {
1096
+ nextPagePromise = null;
1097
+ });
1098
+ }
1099
+ return nextPagePromise;
1100
+ },
1101
+ async all() {
1102
+ const items = [...this.data];
1103
+ let current = this;
1104
+ while (current) {
1105
+ if (!current.pagination.hasMore) break;
1106
+ current = await current.nextPage();
1107
+ if (!current) break;
1108
+ items.push(...current.data);
1109
+ }
1110
+ return items;
1111
+ },
1112
+ [Symbol.asyncIterator]() {
1113
+ let current = this;
1114
+ let index = 0;
1115
+ return {
1116
+ async next() {
1117
+ while (current) {
1118
+ if (index < current.data.length) {
1119
+ return { done: false, value: current.data[index++] };
1120
+ }
1121
+ if (!current.pagination.hasMore) {
1122
+ current = null;
1123
+ break;
1124
+ }
1125
+ current = await current.nextPage();
1126
+ index = 0;
1127
+ }
1128
+ return { done: true, value: void 0 };
1129
+ }
1130
+ };
1131
+ }
1132
+ };
1133
+ return page;
1134
+ }
1135
+ function createPageResult(dataOrRaw, paginationOrFetchNext, fetchNextOrMeta, meta) {
1136
+ if (Array.isArray(dataOrRaw)) {
1137
+ const data = dataOrRaw;
1138
+ const pagination = paginationOrFetchNext;
1139
+ const fetchNextPage2 = fetchNextOrMeta;
1140
+ const fetchNext2 = async () => {
1141
+ if (!fetchNextPage2) return null;
1142
+ return fetchNextPage2.length > 0 ? fetchNextPage2(
1143
+ pagination.cursor
1144
+ ) : fetchNextPage2();
1145
+ };
1146
+ return buildPageResult(data, pagination, fetchNext2, meta);
1147
+ }
1148
+ const raw = dataOrRaw;
1149
+ const fetchNextPage = paginationOrFetchNext;
1150
+ const fetchNext = async () => {
1151
+ if (!fetchNextPage) return null;
1152
+ return fetchNextPage.length > 0 ? fetchNextPage(
1153
+ raw.pagination.cursor
1154
+ ) : fetchNextPage();
1155
+ };
1156
+ return buildPageResult(
1157
+ Array.isArray(raw.data) ? raw.data : [],
1158
+ raw.pagination,
1159
+ fetchNext,
1160
+ raw.meta
1161
+ );
1162
+ }
1163
+
1164
+ // src/constants.ts
1165
+ var DEFAULT_ONTOLOGY_BASE_URL = "https://api.frontal.dev/v1";
1166
+ var VERSION = "0.0.1";
1167
+ var DEFAULT_TIMEOUT = 3e4;
1168
+ var DEFAULT_MAX_RETRIES = 3;
1169
+ var DEFAULT_RETRY_DELAY = 1e3;
1170
+
1171
+ // src/sdk.ts
1172
+ var OntologySdk = class {
1173
+ engine;
1174
+ objects;
1175
+ relationships;
1176
+ schemas;
1177
+ versions;
1178
+ validation;
1179
+ transformations;
1180
+ reasoning;
1181
+ rollouts;
1182
+ rollups;
1183
+ extract;
1184
+ events;
1185
+ /**
1186
+ * @param http - The HTTP client used to make API requests.
1187
+ */
348
1188
  constructor(http) {
1189
+ this.engine = new EngineNamespace(http);
1190
+ this.objects = new ObjectsNamespace(http);
1191
+ this.relationships = new RelationshipsNamespace(http);
1192
+ this.schemas = new SchemasNamespace(http);
1193
+ this.versions = new VersionsNamespace(http);
1194
+ this.validation = new ValidationNamespace(http);
1195
+ this.transformations = new TransformationsNamespace(http);
1196
+ this.reasoning = new ReasoningNamespace(http);
1197
+ this.rollouts = new RolloutsNamespace(http);
1198
+ this.rollups = new RollupsNamespace(http);
1199
+ this.extract = new ExtractNamespace(http);
1200
+ this.events = new EventsNamespace(http);
1201
+ }
1202
+ };
1203
+ var SubdomainBase = class {
1204
+ constructor(http, base) {
349
1205
  this.http = http;
1206
+ this.base = base;
350
1207
  }
351
- list() {
352
- return __async(this, null, function* () {
353
- return this.http.get("/ontology/engine/runs");
354
- });
1208
+ /**
1209
+ * Returns the capabilities of this subdomain service.
1210
+ */
1211
+ capabilities() {
1212
+ return this.http.get(`${this.base}/capabilities`);
355
1213
  }
356
- create(definition) {
357
- return __async(this, null, function* () {
358
- const body = RuleDefinitionSchema.parse(definition);
359
- return this.http.post("/ontology/engine/runs", body);
360
- });
1214
+ /**
1215
+ * Health check for this subdomain service.
1216
+ */
1217
+ health() {
1218
+ return this.http.get(`${this.base}/health`);
361
1219
  }
362
- update(_ruleId, definition) {
363
- return __async(this, null, function* () {
364
- return this.http.post("/ontology/engine/runs", definition);
365
- });
1220
+ /**
1221
+ * Returns service info/metadata for this subdomain service.
1222
+ */
1223
+ info() {
1224
+ return this.http.get(`${this.base}/info`);
366
1225
  }
367
- delete(ruleId) {
368
- return __async(this, null, function* () {
369
- return this.http.post("/ontology/engine/runs", {
370
- action: "delete-rule",
371
- ruleId
372
- });
373
- });
1226
+ /**
1227
+ * Lists asynchronous runs for this subdomain.
1228
+ * @param opts - Pagination options.
1229
+ */
1230
+ async runs(opts = {}) {
1231
+ const raw = await this.http.get(`${this.base}/runs`, opts);
1232
+ return createPageResult(
1233
+ asPagePayload(raw),
1234
+ (c) => this.runs({ ...opts, cursor: c })
1235
+ );
374
1236
  }
375
- evaluate(opts) {
376
- return __async(this, null, function* () {
377
- return this.http.post("/ontology/engine/ontologies/validate", opts);
378
- });
1237
+ /**
1238
+ * Creates a new asynchronous run.
1239
+ * @param input - The run input payload.
1240
+ */
1241
+ createRun(input) {
1242
+ return this.http.post(`${this.base}/runs`, input);
1243
+ }
1244
+ /**
1245
+ * Fetches an asynchronous run by ID.
1246
+ * @param runId - The run ID.
1247
+ */
1248
+ run(runId) {
1249
+ return this.http.get(`${this.base}/runs/${runId}`);
379
1250
  }
380
1251
  };
381
- var MixinsNamespace = class {
1252
+ var EngineNamespace = class extends SubdomainBase {
382
1253
  constructor(http) {
383
- this.http = http;
1254
+ super(http, "/ontology/engine");
384
1255
  }
385
- list() {
386
- return __async(this, null, function* () {
387
- return this.http.get("/ontology/engine/runs");
388
- });
1256
+ /**
1257
+ * Generates an ontology from a description.
1258
+ * @param input - Generation parameters.
1259
+ */
1260
+ generate(input) {
1261
+ return this.http.post("/ontology/engine/ontologies/generate", input);
389
1262
  }
390
- create(definition) {
391
- return __async(this, null, function* () {
392
- const body = MixinDefinitionSchema.parse(definition);
393
- return this.http.post("/ontology/engine/runs", body);
394
- });
1263
+ /**
1264
+ * Validates an ontology definition.
1265
+ * @param input - The ontology to validate.
1266
+ */
1267
+ validate(input) {
1268
+ return this.http.post("/ontology/engine/ontologies/validate", input);
1269
+ }
1270
+ /**
1271
+ * Exports an ontology in a standard format.
1272
+ * @param input - Export parameters.
1273
+ */
1274
+ export(input) {
1275
+ return this.http.post("/ontology/engine/ontologies/export", input);
1276
+ }
1277
+ /**
1278
+ * Exports an ontology as SHACL shapes.
1279
+ * @param input - Export parameters.
1280
+ */
1281
+ exportShacl(input) {
1282
+ return this.http.post("/ontology/engine/ontologies/export-shacl", input);
1283
+ }
1284
+ /**
1285
+ * Infers class definitions from source data.
1286
+ * @param input - Inference parameters.
1287
+ */
1288
+ inferClasses(input) {
1289
+ return this.http.post("/ontology/engine/ontologies/infer-classes", input);
1290
+ }
1291
+ /**
1292
+ * Infers property definitions from source data.
1293
+ * @param input - Inference parameters.
1294
+ */
1295
+ inferProperties(input) {
1296
+ return this.http.post(
1297
+ "/ontology/engine/ontologies/infer-properties",
1298
+ input
1299
+ );
1300
+ }
1301
+ /**
1302
+ * Compares two ontology versions.
1303
+ * @param input - Comparison parameters (fromVersion, toVersion).
1304
+ */
1305
+ compareVersions(input) {
1306
+ return this.http.post(
1307
+ "/ontology/engine/ontologies/compare-versions",
1308
+ input
1309
+ );
395
1310
  }
396
1311
  };
397
- var GenerationNamespace = class {
1312
+ var ObjectsNamespace = class extends SubdomainBase {
398
1313
  constructor(http) {
399
- this.http = http;
1314
+ super(http, "/ontology/objects");
400
1315
  }
401
- generate(description, opts) {
402
- return __async(this, null, function* () {
403
- return this.http.post("/ontology/engine/ontologies/generate", __spreadValues({
404
- description
405
- }, opts));
406
- });
1316
+ /**
1317
+ * Lists object types with pagination.
1318
+ * @param opts - Pagination options.
1319
+ */
1320
+ async listObjectTypes(opts = {}) {
1321
+ const raw = await this.http.get("/ontology/objects/object-types", opts);
1322
+ return createPageResult(
1323
+ asPagePayload(raw),
1324
+ (c) => this.listObjectTypes({ ...opts, cursor: c })
1325
+ );
407
1326
  }
408
- infer(opts) {
409
- return __async(this, null, function* () {
410
- return this.http.post("/ontology/engine/ontologies/infer-classes", opts);
411
- });
1327
+ /**
1328
+ * Fetches an object type by ID.
1329
+ * @param id - The object type ID.
1330
+ */
1331
+ getObjectType(id) {
1332
+ return this.http.get(`/ontology/objects/object-types/${id}`);
412
1333
  }
413
- suggestions() {
414
- return __async(this, arguments, function* (opts = {}) {
415
- return this.http.get("/ontology/engine/runs", opts);
416
- });
1334
+ /**
1335
+ * Creates or updates an object type.
1336
+ * @param id - The object type ID.
1337
+ * @param body - The object type definition.
1338
+ */
1339
+ putObjectType(id, body) {
1340
+ return this.http.put(`/ontology/objects/object-types/${id}`, body);
417
1341
  }
418
- acceptSuggestion(_suggestionId) {
419
- return __async(this, null, function* () {
420
- return this.http.post("/ontology/engine/runs");
421
- });
1342
+ /**
1343
+ * Deletes an object type.
1344
+ * @param id - The object type ID.
1345
+ */
1346
+ deleteObjectType(id) {
1347
+ return this.http.delete(`/ontology/objects/object-types/${id}`);
422
1348
  }
423
- rejectSuggestion(_suggestionId, reason) {
424
- return __async(this, null, function* () {
425
- return this.http.post("/ontology/engine/runs", {
426
- reason
427
- });
428
- });
1349
+ /**
1350
+ * Lists object instances with pagination.
1351
+ * @param opts - Pagination options.
1352
+ */
1353
+ async listObjects(opts = {}) {
1354
+ const raw = await this.http.get("/ontology/objects/objects", opts);
1355
+ return createPageResult(
1356
+ asPagePayload(raw),
1357
+ (c) => this.listObjects({ ...opts, cursor: c })
1358
+ );
1359
+ }
1360
+ /**
1361
+ * Fetches an object instance by ID.
1362
+ * @param id - The object ID.
1363
+ */
1364
+ getObject(id) {
1365
+ return this.http.get(`/ontology/objects/objects/${id}`);
1366
+ }
1367
+ /**
1368
+ * Creates or updates an object instance.
1369
+ * @param id - The object ID.
1370
+ * @param body - The object data.
1371
+ */
1372
+ putObject(id, body) {
1373
+ return this.http.put(`/ontology/objects/objects/${id}`, body);
1374
+ }
1375
+ /**
1376
+ * Deletes an object instance.
1377
+ * @param id - The object ID.
1378
+ */
1379
+ deleteObject(id) {
1380
+ return this.http.delete(`/ontology/objects/objects/${id}`);
1381
+ }
1382
+ };
1383
+ var RelationshipsNamespace = class extends SubdomainBase {
1384
+ constructor(http) {
1385
+ super(http, "/ontology/relationships");
1386
+ }
1387
+ /**
1388
+ * Lists relationship types with pagination.
1389
+ * @param opts - Pagination options.
1390
+ */
1391
+ async listTypes(opts = {}) {
1392
+ const raw = await this.http.get(
1393
+ "/ontology/relationships/relationship-types",
1394
+ opts
1395
+ );
1396
+ return createPageResult(
1397
+ asPagePayload(raw),
1398
+ (c) => this.listTypes({ ...opts, cursor: c })
1399
+ );
1400
+ }
1401
+ /**
1402
+ * Deletes a relationship type.
1403
+ * @param id - The relationship type ID.
1404
+ */
1405
+ deleteType(id) {
1406
+ return this.http.delete(`/ontology/relationships/relationship-types/${id}`);
1407
+ }
1408
+ /**
1409
+ * Lists relationship instances with pagination.
1410
+ * @param opts - Pagination options.
1411
+ */
1412
+ async list(opts = {}) {
1413
+ const raw = await this.http.get(
1414
+ "/ontology/relationships/relationships",
1415
+ opts
1416
+ );
1417
+ return createPageResult(
1418
+ asPagePayload(raw),
1419
+ (c) => this.list({ ...opts, cursor: c })
1420
+ );
1421
+ }
1422
+ /**
1423
+ * Fetches a relationship instance by ID.
1424
+ * @param id - The relationship ID.
1425
+ */
1426
+ get(id) {
1427
+ return this.http.get(`/ontology/relationships/relationships/${id}`);
1428
+ }
1429
+ /**
1430
+ * Creates or updates a relationship instance.
1431
+ * @param id - The relationship ID.
1432
+ * @param body - The relationship data.
1433
+ */
1434
+ put(id, body) {
1435
+ return this.http.put(`/ontology/relationships/relationships/${id}`, body);
1436
+ }
1437
+ /**
1438
+ * Deletes a relationship instance.
1439
+ * @param id - The relationship ID.
1440
+ */
1441
+ delete(id) {
1442
+ return this.http.delete(`/ontology/relationships/relationships/${id}`);
1443
+ }
1444
+ };
1445
+ var SchemasNamespace = class extends SubdomainBase {
1446
+ constructor(http) {
1447
+ super(http, "/ontology/schemas");
1448
+ }
1449
+ /**
1450
+ * Lists schema definitions with pagination.
1451
+ * @param opts - Pagination options.
1452
+ */
1453
+ async list(opts = {}) {
1454
+ const raw = await this.http.get("/ontology/schemas/schemas", opts);
1455
+ return createPageResult(
1456
+ asPagePayload(raw),
1457
+ (c) => this.list({ ...opts, cursor: c })
1458
+ );
1459
+ }
1460
+ /**
1461
+ * Creates a new schema definition.
1462
+ * @param body - The schema definition.
1463
+ */
1464
+ create(body) {
1465
+ return this.http.post("/ontology/schemas/schemas", body);
1466
+ }
1467
+ /**
1468
+ * Validates a schema definition.
1469
+ * @param body - The schema to validate.
1470
+ */
1471
+ validate(body) {
1472
+ return this.http.post("/ontology/schemas/schemas/validate", body);
1473
+ }
1474
+ /**
1475
+ * Fetches a schema definition by ID.
1476
+ * @param id - The schema ID.
1477
+ */
1478
+ get(id) {
1479
+ return this.http.get(`/ontology/schemas/schemas/${id}`);
1480
+ }
1481
+ /**
1482
+ * Deletes a schema definition.
1483
+ * @param id - The schema ID.
1484
+ */
1485
+ delete(id) {
1486
+ return this.http.delete(`/ontology/schemas/schemas/${id}`);
1487
+ }
1488
+ };
1489
+ var VersionsNamespace = class extends SubdomainBase {
1490
+ constructor(http) {
1491
+ super(http, "/ontology/versions");
1492
+ }
1493
+ /**
1494
+ * Creates a new version.
1495
+ * @param body - Version creation payload.
1496
+ */
1497
+ create(body) {
1498
+ return this.http.post("/ontology/versions/versions", body);
1499
+ }
1500
+ /**
1501
+ * Compares two versions.
1502
+ * @param body - Comparison parameters.
1503
+ */
1504
+ compare(body) {
1505
+ return this.http.post("/ontology/versions/versions/compare", body);
1506
+ }
1507
+ /**
1508
+ * Fetches a version by ID.
1509
+ * @param id - The version ID.
1510
+ */
1511
+ get(id) {
1512
+ return this.http.get(`/ontology/versions/versions/${id}`);
1513
+ }
1514
+ /**
1515
+ * Deletes a version.
1516
+ * @param id - The version ID.
1517
+ */
1518
+ delete(id) {
1519
+ return this.http.delete(`/ontology/versions/versions/${id}`);
1520
+ }
1521
+ /**
1522
+ * Verifies an audit trail for a version.
1523
+ * @param body - Audit verification payload.
1524
+ */
1525
+ auditVerify(body) {
1526
+ return this.http.post("/ontology/versions/audit/verify", body);
1527
+ }
1528
+ /**
1529
+ * Lists release bundles with pagination.
1530
+ * @param opts - Pagination options.
1531
+ */
1532
+ async listReleaseBundles(opts = {}) {
1533
+ const raw = await this.http.get("/ontology/versions/release-bundles", opts);
1534
+ return createPageResult(
1535
+ asPagePayload(raw),
1536
+ (c) => this.listReleaseBundles({ ...opts, cursor: c })
1537
+ );
1538
+ }
1539
+ /**
1540
+ * Creates a new release bundle.
1541
+ * @param body - Release bundle payload.
1542
+ */
1543
+ createReleaseBundle(body) {
1544
+ return this.http.post("/ontology/versions/release-bundles", body);
1545
+ }
1546
+ /**
1547
+ * Fetches a release bundle by ID.
1548
+ * @param id - The release bundle ID.
1549
+ */
1550
+ getReleaseBundle(id) {
1551
+ return this.http.get(`/ontology/versions/release-bundles/${id}`);
1552
+ }
1553
+ };
1554
+ var ValidationNamespace = class extends SubdomainBase {
1555
+ constructor(http) {
1556
+ super(http, "/ontology/validation");
1557
+ }
1558
+ /**
1559
+ * Validates a payload against a schema.
1560
+ * @param body - The payload to validate.
1561
+ */
1562
+ validatePayload(body) {
1563
+ return this.http.post("/ontology/validation/payloads/validate", body);
1564
+ }
1565
+ /**
1566
+ * Lists validation rules with pagination.
1567
+ * @param opts - Pagination options.
1568
+ */
1569
+ async listRules(opts = {}) {
1570
+ const raw = await this.http.get("/ontology/validation/rules", opts);
1571
+ return createPageResult(
1572
+ asPagePayload(raw),
1573
+ (c) => this.listRules({ ...opts, cursor: c })
1574
+ );
1575
+ }
1576
+ /**
1577
+ * Creates a validation rule.
1578
+ * @param body - The rule definition.
1579
+ */
1580
+ createRule(body) {
1581
+ return this.http.post("/ontology/validation/rules", body);
1582
+ }
1583
+ /**
1584
+ * Fetches a validation rule by ID.
1585
+ * @param id - The rule ID.
1586
+ */
1587
+ getRule(id) {
1588
+ return this.http.get(`/ontology/validation/rules/${id}`);
1589
+ }
1590
+ /**
1591
+ * Deletes a validation rule.
1592
+ * @param id - The rule ID.
1593
+ */
1594
+ deleteRule(id) {
1595
+ return this.http.delete(`/ontology/validation/rules/${id}`);
1596
+ }
1597
+ };
1598
+ var TransformationsNamespace = class extends SubdomainBase {
1599
+ constructor(http) {
1600
+ super(http, "/ontology/transformations");
1601
+ }
1602
+ /**
1603
+ * Creates a data transformation.
1604
+ * @param body - The transformation definition.
1605
+ */
1606
+ create(body) {
1607
+ return this.http.post("/ontology/transformations/transformations", body);
1608
+ }
1609
+ };
1610
+ var ReasoningNamespace = class extends SubdomainBase {
1611
+ constructor(http) {
1612
+ super(http, "/ontology/reasoning");
1613
+ }
1614
+ /**
1615
+ * Generates an explanation for a reasoning result.
1616
+ * @param body - Explanation request.
1617
+ */
1618
+ explain(body) {
1619
+ return this.http.post("/ontology/reasoning/explain", body);
1620
+ }
1621
+ /**
1622
+ * Retrieves facts based on criteria.
1623
+ * @param body - Fact query parameters.
1624
+ */
1625
+ facts(body) {
1626
+ return this.http.post("/ontology/reasoning/facts", body);
1627
+ }
1628
+ /**
1629
+ * Loads facts into the reasoning graph.
1630
+ * @param body - Facts graph data.
1631
+ */
1632
+ loadFactsGraph(body) {
1633
+ return this.http.post("/ontology/reasoning/facts/load-graph", body);
1634
+ }
1635
+ /**
1636
+ * Performs forward chaining reasoning.
1637
+ * @param body - Forward reasoning parameters.
1638
+ */
1639
+ reasonForward(body) {
1640
+ return this.http.post("/ontology/reasoning/reason/forward", body);
1641
+ }
1642
+ /**
1643
+ * Performs backward chaining reasoning.
1644
+ * @param body - Backward reasoning parameters.
1645
+ */
1646
+ reasonBackward(body) {
1647
+ return this.http.post("/ontology/reasoning/reason/backward", body);
1648
+ }
1649
+ /**
1650
+ * Lists reasoning rules with pagination.
1651
+ * @param opts - Pagination options.
1652
+ */
1653
+ async listRules(opts = {}) {
1654
+ const raw = await this.http.get("/ontology/reasoning/rules", opts);
1655
+ return createPageResult(
1656
+ asPagePayload(raw),
1657
+ (c) => this.listRules({ ...opts, cursor: c })
1658
+ );
1659
+ }
1660
+ /**
1661
+ * Creates a reasoning rule.
1662
+ * @param body - The rule definition.
1663
+ */
1664
+ createRule(body) {
1665
+ return this.http.post("/ontology/reasoning/rules", body);
1666
+ }
1667
+ /**
1668
+ * Updates a reasoning rule.
1669
+ * @param id - The rule ID.
1670
+ * @param body - The updated rule fields.
1671
+ */
1672
+ updateRule(id, body) {
1673
+ return this.http.put(`/ontology/reasoning/rules/${id}`, body);
1674
+ }
1675
+ /**
1676
+ * Deletes a reasoning rule.
1677
+ * @param id - The rule ID.
1678
+ */
1679
+ deleteRule(id) {
1680
+ return this.http.delete(`/ontology/reasoning/rules/${id}`);
1681
+ }
1682
+ };
1683
+ var RolloutsNamespace = class extends SubdomainBase {
1684
+ constructor(http) {
1685
+ super(http, "/ontology/rollouts");
1686
+ }
1687
+ /**
1688
+ * Lists rollouts with pagination.
1689
+ * @param opts - Pagination options.
1690
+ */
1691
+ async list(opts = {}) {
1692
+ const raw = await this.http.get("/ontology/rollouts/rollouts", opts);
1693
+ return createPageResult(
1694
+ asPagePayload(raw),
1695
+ (c) => this.list({ ...opts, cursor: c })
1696
+ );
1697
+ }
1698
+ /**
1699
+ * Creates a new rollout.
1700
+ * @param body - Rollout configuration.
1701
+ */
1702
+ create(body) {
1703
+ return this.http.post("/ontology/rollouts/rollouts", body);
1704
+ }
1705
+ /**
1706
+ * Fetches a rollout by ID.
1707
+ * @param id - The rollout ID.
1708
+ */
1709
+ get(id) {
1710
+ return this.http.get(`/ontology/rollouts/rollouts/${id}`);
1711
+ }
1712
+ /**
1713
+ * Updates a rollout.
1714
+ * @param id - The rollout ID.
1715
+ * @param body - The updated rollout fields.
1716
+ */
1717
+ update(id, body) {
1718
+ return this.http.put(`/ontology/rollouts/rollouts/${id}`, body);
1719
+ }
1720
+ /**
1721
+ * Deletes a rollout.
1722
+ * @param id - The rollout ID.
1723
+ */
1724
+ delete(id) {
1725
+ return this.http.delete(`/ontology/rollouts/rollouts/${id}`);
1726
+ }
1727
+ /**
1728
+ * Starts a rollout.
1729
+ * @param id - The rollout ID.
1730
+ * @param body - Start parameters.
1731
+ */
1732
+ start(id, body = {}) {
1733
+ return this.http.post(`/ontology/rollouts/rollouts/${id}/start`, body);
1734
+ }
1735
+ /**
1736
+ * Pauses a rollout.
1737
+ * @param id - The rollout ID.
1738
+ * @param body - Pause parameters.
1739
+ */
1740
+ pause(id, body = {}) {
1741
+ return this.http.post(`/ontology/rollouts/rollouts/${id}/pause`, body);
1742
+ }
1743
+ /**
1744
+ * Resumes a paused rollout.
1745
+ * @param id - The rollout ID.
1746
+ * @param body - Resume parameters.
1747
+ */
1748
+ resume(id, body = {}) {
1749
+ return this.http.post(`/ontology/rollouts/rollouts/${id}/resume`, body);
1750
+ }
1751
+ /**
1752
+ * Rolls back a rollout.
1753
+ * @param id - The rollout ID.
1754
+ * @param body - Rollback parameters.
1755
+ */
1756
+ rollback(id, body = {}) {
1757
+ return this.http.post(`/ontology/rollouts/rollouts/${id}/rollback`, body);
1758
+ }
1759
+ /**
1760
+ * Returns the current status of a rollout.
1761
+ * @param id - The rollout ID.
1762
+ */
1763
+ status(id) {
1764
+ return this.http.get(`/ontology/rollouts/rollouts/${id}/status`);
1765
+ }
1766
+ };
1767
+ var RollupsNamespace = class extends SubdomainBase {
1768
+ constructor(http) {
1769
+ super(http, "/ontology/rollups");
1770
+ }
1771
+ /**
1772
+ * Lists rollups with pagination.
1773
+ * @param opts - Pagination options.
1774
+ */
1775
+ async list(opts = {}) {
1776
+ const raw = await this.http.get("/ontology/rollups/rollups", opts);
1777
+ return createPageResult(
1778
+ asPagePayload(raw),
1779
+ (c) => this.list({ ...opts, cursor: c })
1780
+ );
1781
+ }
1782
+ /**
1783
+ * Creates a rollup job.
1784
+ * @param body - Rollup configuration.
1785
+ */
1786
+ create(body) {
1787
+ return this.http.post("/ontology/rollups/rollups", body);
1788
+ }
1789
+ /**
1790
+ * Fetches a rollup by ID.
1791
+ * @param id - The rollup ID.
1792
+ */
1793
+ get(id) {
1794
+ return this.http.get(`/ontology/rollups/rollups/${id}`);
1795
+ }
1796
+ /**
1797
+ * Updates a rollup.
1798
+ * @param id - The rollup ID.
1799
+ * @param body - The updated rollup fields.
1800
+ */
1801
+ update(id, body) {
1802
+ return this.http.put(`/ontology/rollups/rollups/${id}`, body);
1803
+ }
1804
+ /**
1805
+ * Deletes a rollup.
1806
+ * @param id - The rollup ID.
1807
+ */
1808
+ delete(id) {
1809
+ return this.http.delete(`/ontology/rollups/rollups/${id}`);
1810
+ }
1811
+ /**
1812
+ * Executes a rollup.
1813
+ * @param id - The rollup ID.
1814
+ * @param body - Execution parameters.
1815
+ */
1816
+ execute(id, body = {}) {
1817
+ return this.http.post(`/ontology/rollups/rollups/${id}/execute`, body);
1818
+ }
1819
+ /**
1820
+ * Previews a rollup result without persisting it.
1821
+ * @param id - The rollup ID.
1822
+ * @param body - Preview parameters.
1823
+ */
1824
+ preview(id, body = {}) {
1825
+ return this.http.post(`/ontology/rollups/rollups/${id}/preview`, body);
1826
+ }
1827
+ /**
1828
+ * Fetches the result of a rollup execution.
1829
+ * @param id - The rollup ID.
1830
+ */
1831
+ result(id) {
1832
+ return this.http.get(`/ontology/rollups/rollups/${id}/result`);
1833
+ }
1834
+ /**
1835
+ * Fetches the result of a specific rollup execution.
1836
+ * @param executionId - The execution ID.
1837
+ */
1838
+ executionResult(executionId) {
1839
+ return this.http.get(`/ontology/rollups/rollup-results/${executionId}`);
1840
+ }
1841
+ };
1842
+ var ExtractNamespace = class extends SubdomainBase {
1843
+ constructor(http) {
1844
+ super(http, "/ontology/extract");
1845
+ }
1846
+ /**
1847
+ * Analyzes source data for extraction.
1848
+ * @param body - Analysis parameters.
1849
+ */
1850
+ analyze(body) {
1851
+ return this.http.post("/ontology/extract/extract/analyze", body);
1852
+ }
1853
+ /**
1854
+ * Extracts architecture from source data.
1855
+ * @param body - Architecture extraction parameters.
1856
+ */
1857
+ architecture(body) {
1858
+ return this.http.post("/ontology/extract/extract/architecture", body);
1859
+ }
1860
+ /**
1861
+ * Extracts coreference chains from source data.
1862
+ * @param body - Coreference extraction parameters.
1863
+ */
1864
+ coreferences(body) {
1865
+ return this.http.post("/ontology/extract/extract/coreferences", body);
1866
+ }
1867
+ /**
1868
+ * Extracts entities from source data.
1869
+ * @param body - Entity extraction parameters.
1870
+ */
1871
+ entities(body) {
1872
+ return this.http.post("/ontology/extract/extract/entities", body);
1873
+ }
1874
+ /**
1875
+ * Extracts events from source data.
1876
+ * @param body - Event extraction parameters.
1877
+ */
1878
+ events(body) {
1879
+ return this.http.post("/ontology/extract/extract/events", body);
1880
+ }
1881
+ /**
1882
+ * Extracts relations from source data.
1883
+ * @param body - Relation extraction parameters.
1884
+ */
1885
+ relations(body) {
1886
+ return this.http.post("/ontology/extract/extract/relations", body);
1887
+ }
1888
+ /**
1889
+ * Extracts RDF triplets from source data.
1890
+ * @param body - Triplet extraction parameters.
1891
+ */
1892
+ triplets(body) {
1893
+ return this.http.post("/ontology/extract/extract/triplets", body);
1894
+ }
1895
+ };
1896
+ var EventsNamespace = class extends SubdomainBase {
1897
+ constructor(http) {
1898
+ super(http, "/ontology/events");
1899
+ }
1900
+ /**
1901
+ * Lists events with pagination.
1902
+ * @param opts - Pagination options.
1903
+ */
1904
+ async list(opts = {}) {
1905
+ const raw = await this.http.get("/ontology/events/events", opts);
1906
+ return createPageResult(
1907
+ asPagePayload(raw),
1908
+ (c) => this.list({ ...opts, cursor: c })
1909
+ );
1910
+ }
1911
+ /**
1912
+ * Creates a new event.
1913
+ * @param body - The event payload.
1914
+ */
1915
+ create(body) {
1916
+ return this.http.post("/ontology/events/events", body);
1917
+ }
1918
+ /**
1919
+ * Fetches an event by ID.
1920
+ * @param id - The event ID.
1921
+ */
1922
+ get(id) {
1923
+ return this.http.get(`/ontology/events/events/${id}`);
1924
+ }
1925
+ /**
1926
+ * Creates an event checkpoint for a consumer.
1927
+ * @param body - Checkpoint data.
1928
+ */
1929
+ createCheckpoint(body) {
1930
+ return this.http.post("/ontology/events/events/checkpoints", body);
1931
+ }
1932
+ /**
1933
+ * Fetches the checkpoint for a consumer.
1934
+ * @param consumer - The consumer identifier.
1935
+ */
1936
+ getCheckpoint(consumer) {
1937
+ return this.http.get(`/ontology/events/events/checkpoints/${consumer}`);
1938
+ }
1939
+ /**
1940
+ * Acquires a lease for event processing.
1941
+ * @param body - Lease acquisition parameters.
1942
+ */
1943
+ acquireLease(body) {
1944
+ return this.http.post("/ontology/events/events/leases/acquire", body);
1945
+ }
1946
+ /**
1947
+ * Acknowledges a lease after processing.
1948
+ * @param body - Lease acknowledgment parameters.
1949
+ */
1950
+ acknowledgeLease(body) {
1951
+ return this.http.post("/ontology/events/events/leases/acknowledge", body);
429
1952
  }
430
1953
  };
431
1954
 
432
- // src/index.ts
1955
+ // src/client.ts
433
1956
  function createOntologyClient(clientOrConfig) {
434
- var _a, _b, _c, _d, _e;
435
- if (clientOrConfig instanceof import_core3.FrontalClient) {
436
- return new OntologyService(clientOrConfig._http);
1957
+ if (clientOrConfig instanceof FrontalClient) {
1958
+ return new OntologySdk(clientOrConfig.httpClient);
437
1959
  }
438
- const http = new import_core3.HttpClient({
1960
+ const http = new HttpClient({
439
1961
  apiKey: clientOrConfig.apiKey,
440
- baseUrl: (_c = (_b = (_a = clientOrConfig.baseUrl) != null ? _a : process.env.FRONTAL_ONTOLOGY_API_URL) != null ? _b : process.env.FRONTAL_API_URL) != null ? _c : "https://api.frontal.dev/v1",
441
- timeout: (_d = clientOrConfig.timeout) != null ? _d : 3e4,
442
- maxRetries: (_e = clientOrConfig.maxRetries) != null ? _e : 3,
443
- retryDelay: 1e3,
1962
+ baseUrl: clientOrConfig.baseUrl ?? env.FRONTAL_API_URL ?? DEFAULT_ONTOLOGY_BASE_URL,
1963
+ timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT,
1964
+ maxRetries: clientOrConfig.maxRetries ?? DEFAULT_MAX_RETRIES,
1965
+ retryDelay: DEFAULT_RETRY_DELAY,
444
1966
  headers: {},
445
- environment: "production",
446
- debug: false
1967
+ environment: env.FRONTAL_ENV,
1968
+ debug: env.FRONTAL_DEBUG ?? false
447
1969
  });
448
- return new OntologyService(http);
1970
+ return new OntologySdk(http);
449
1971
  }
450
- var ontology = new OntologyService((0, import_core3.getDefaultClient)()._http);
1972
+ var _ontologyCache;
1973
+ var ontology = new Proxy({}, {
1974
+ get(_t, prop) {
1975
+ if (!_ontologyCache) {
1976
+ _ontologyCache = createOntologyClient(getDefaultClient());
1977
+ }
1978
+ const inst = _ontologyCache;
1979
+ const val = inst[prop];
1980
+ return typeof val === "function" ? val.bind(inst) : val;
1981
+ }
1982
+ });
1983
+
1984
+ // src/schemas.ts
1985
+ var import_zod5 = require("zod");
1986
+ var FieldTypeSchema = import_zod5.z.enum([
1987
+ "string",
1988
+ "integer",
1989
+ "float",
1990
+ "boolean",
1991
+ "uuid",
1992
+ "timestamp",
1993
+ "currency",
1994
+ "json",
1995
+ "array",
1996
+ "enum",
1997
+ "vector",
1998
+ "text"
1999
+ ]);
2000
+ var RelationshipTypeSchema = import_zod5.z.enum([
2001
+ "hasOne",
2002
+ "hasMany",
2003
+ "belongsTo",
2004
+ "manyToMany"
2005
+ ]);
2006
+ var FieldDefinitionSchema = import_zod5.z.object({
2007
+ type: FieldTypeSchema,
2008
+ required: import_zod5.z.boolean().default(false),
2009
+ primary: import_zod5.z.boolean().default(false),
2010
+ unique: import_zod5.z.boolean().default(false),
2011
+ default: import_zod5.z.unknown().optional(),
2012
+ substrate: import_zod5.z.string().optional(),
2013
+ computed: import_zod5.z.boolean().optional(),
2014
+ derivedBy: import_zod5.z.string().optional(),
2015
+ cache: import_zod5.z.object({
2016
+ ttl: import_zod5.z.string()
2017
+ }).optional(),
2018
+ auto: import_zod5.z.boolean().optional(),
2019
+ enum: import_zod5.z.array(import_zod5.z.string()).optional(),
2020
+ dimensions: import_zod5.z.number().int().optional(),
2021
+ items: import_zod5.z.string().optional(),
2022
+ description: import_zod5.z.string().optional()
2023
+ }).loose();
2024
+ var RelationshipDefinitionSchema = import_zod5.z.object({
2025
+ name: import_zod5.z.string().optional(),
2026
+ type: RelationshipTypeSchema,
2027
+ targetEntity: import_zod5.z.string(),
2028
+ foreignKey: import_zod5.z.string().optional(),
2029
+ substrate: import_zod5.z.string().optional(),
2030
+ cascade: import_zod5.z.object({
2031
+ delete: import_zod5.z.enum(["hard", "soft", "restrict", "nullify"]),
2032
+ update: import_zod5.z.enum(["cascade", "restrict"])
2033
+ }).optional(),
2034
+ computed: import_zod5.z.record(import_zod5.z.string(), import_zod5.z.unknown()).optional(),
2035
+ description: import_zod5.z.string().optional()
2036
+ }).loose();
2037
+ var SubstrateRoutingSchema = import_zod5.z.object({
2038
+ operational: import_zod5.z.string().optional(),
2039
+ analytical: import_zod5.z.string().optional(),
2040
+ semantic: import_zod5.z.string().optional(),
2041
+ cache: import_zod5.z.string().optional()
2042
+ }).loose();
2043
+ var SemanticMetadataSchema = import_zod5.z.object({
2044
+ description: import_zod5.z.string().optional(),
2045
+ lifecycle: import_zod5.z.array(import_zod5.z.string()).optional(),
2046
+ criticalFields: import_zod5.z.array(import_zod5.z.string()).optional(),
2047
+ significantEvents: import_zod5.z.array(import_zod5.z.string()).optional(),
2048
+ tags: import_zod5.z.array(import_zod5.z.string()).optional()
2049
+ }).loose();
2050
+ var IndexDefinitionSchema = import_zod5.z.object({
2051
+ name: import_zod5.z.string().optional(),
2052
+ fields: import_zod5.z.array(import_zod5.z.string()).min(1),
2053
+ substrate: import_zod5.z.string().optional(),
2054
+ unique: import_zod5.z.boolean().default(false),
2055
+ type: import_zod5.z.enum(["btree", "hash", "gin", "gist", "brin"]).default("btree")
2056
+ }).loose();
2057
+ var ModelDefinitionSchema = import_zod5.z.object({
2058
+ name: import_zod5.z.string(),
2059
+ displayName: import_zod5.z.string().optional(),
2060
+ description: import_zod5.z.string().optional(),
2061
+ extends: import_zod5.z.string().optional(),
2062
+ mixins: import_zod5.z.array(import_zod5.z.string()).optional(),
2063
+ fields: import_zod5.z.record(import_zod5.z.string(), FieldDefinitionSchema),
2064
+ relationships: import_zod5.z.record(import_zod5.z.string(), RelationshipDefinitionSchema).optional(),
2065
+ substrates: SubstrateRoutingSchema.optional(),
2066
+ semantics: SemanticMetadataSchema.optional(),
2067
+ indexes: import_zod5.z.array(IndexDefinitionSchema).optional(),
2068
+ status: import_zod5.z.enum(["draft", "active", "deprecated"]).default("draft")
2069
+ }).strict();
2070
+ var ModelSchema = ModelDefinitionSchema.extend({
2071
+ id: import_zod5.z.string(),
2072
+ version: import_zod5.z.number().int(),
2073
+ createdAt: timestampSchema,
2074
+ updatedAt: timestampSchema,
2075
+ entityCount: import_zod5.z.number().int().optional()
2076
+ }).loose();
2077
+ var MigrationPlanSchema = import_zod5.z.object({
2078
+ id: import_zod5.z.string(),
2079
+ modelId: import_zod5.z.string(),
2080
+ fromVersion: import_zod5.z.number().int(),
2081
+ toVersion: import_zod5.z.number().int(),
2082
+ changes: import_zod5.z.array(
2083
+ import_zod5.z.object({
2084
+ type: import_zod5.z.enum([
2085
+ "add-field",
2086
+ "remove-field",
2087
+ "modify-field",
2088
+ "add-relationship",
2089
+ "remove-relationship"
2090
+ ]),
2091
+ description: import_zod5.z.string(),
2092
+ impact: import_zod5.z.enum(["breaking", "non-breaking", "data-loss"]),
2093
+ sql: import_zod5.z.string().optional()
2094
+ })
2095
+ ),
2096
+ riskLevel: import_zod5.z.enum(["low", "medium", "high", "critical"]),
2097
+ estimatedDowntime: import_zod5.z.string().optional(),
2098
+ rolloutStrategy: import_zod5.z.enum([
2099
+ "zero-downtime",
2100
+ "maintenance-window",
2101
+ "immediate"
2102
+ ]),
2103
+ createdAt: timestampSchema
2104
+ }).loose();
2105
+ var RuleDefinitionSchema = import_zod5.z.object({
2106
+ name: import_zod5.z.string(),
2107
+ description: import_zod5.z.string().optional(),
2108
+ entityTypes: import_zod5.z.array(import_zod5.z.string()).min(1),
2109
+ condition: import_zod5.z.string(),
2110
+ action: import_zod5.z.enum(["validate", "transform", "notify"]),
2111
+ severity: import_zod5.z.enum(["error", "warning", "info"]),
2112
+ enabled: import_zod5.z.boolean().default(true)
2113
+ }).strict();
2114
+ var MixinDefinitionSchema = import_zod5.z.object({
2115
+ name: import_zod5.z.string(),
2116
+ description: import_zod5.z.string().optional(),
2117
+ fields: import_zod5.z.record(import_zod5.z.string(), FieldDefinitionSchema),
2118
+ relationships: import_zod5.z.record(import_zod5.z.string(), RelationshipDefinitionSchema).optional(),
2119
+ appliesTo: import_zod5.z.array(import_zod5.z.string()).optional()
2120
+ }).strict();
451
2121
  // Annotate the CommonJS export names for ESM import in node:
452
2122
  0 && (module.exports = {
2123
+ DEFAULT_ONTOLOGY_BASE_URL,
453
2124
  FieldDefinitionSchema,
454
2125
  FieldTypeSchema,
455
2126
  IndexDefinitionSchema,
@@ -457,12 +2128,13 @@ var ontology = new OntologyService((0, import_core3.getDefaultClient)()._http);
457
2128
  MixinDefinitionSchema,
458
2129
  ModelDefinitionSchema,
459
2130
  ModelSchema,
460
- OntologyService,
2131
+ OntologySdk,
461
2132
  RelationshipDefinitionSchema,
462
2133
  RelationshipTypeSchema,
463
2134
  RuleDefinitionSchema,
464
2135
  SemanticMetadataSchema,
465
2136
  SubstrateRoutingSchema,
2137
+ VERSION,
466
2138
  createOntologyClient,
467
2139
  ontology
468
2140
  });