@unispechq/unispec-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,235 @@
1
+ import { UniSpecDocument } from "../types";
2
+
3
+ export type ChangeSeverity = "breaking" | "non-breaking" | "unknown";
4
+
5
+ export interface UniSpecChange {
6
+ path: string;
7
+ description: string;
8
+ severity: ChangeSeverity;
9
+ protocol?: "rest" | "graphql" | "websocket";
10
+ kind?: string;
11
+ }
12
+
13
+ export interface DiffResult {
14
+ changes: UniSpecChange[];
15
+ }
16
+
17
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
18
+ return Object.prototype.toString.call(value) === "[object Object]";
19
+ }
20
+
21
+ function diffValues(oldVal: unknown, newVal: unknown, basePath: string, out: UniSpecChange[]): void {
22
+ if (oldVal === newVal) {
23
+ return;
24
+ }
25
+
26
+ // Both plain objects → recurse by keys
27
+ if (isPlainObject(oldVal) && isPlainObject(newVal)) {
28
+ const oldKeys = new Set(Object.keys(oldVal));
29
+ const newKeys = new Set(Object.keys(newVal));
30
+
31
+ // Removed keys
32
+ for (const key of oldKeys) {
33
+ if (!newKeys.has(key)) {
34
+ out.push({
35
+ path: `${basePath}/${key}`,
36
+ description: "Field removed",
37
+ severity: "unknown",
38
+ });
39
+ }
40
+ }
41
+
42
+ // Added / changed keys
43
+ for (const key of newKeys) {
44
+ const childPath = `${basePath}/${key}`;
45
+ if (!oldKeys.has(key)) {
46
+ out.push({
47
+ path: childPath,
48
+ description: "Field added",
49
+ severity: "unknown",
50
+ });
51
+ continue;
52
+ }
53
+
54
+ diffValues((oldVal as Record<string, unknown>)[key], (newVal as Record<string, unknown>)[key], childPath, out);
55
+ }
56
+
57
+ return;
58
+ }
59
+
60
+ // Arrays → shallow compare by index for now
61
+ if (Array.isArray(oldVal) && Array.isArray(newVal)) {
62
+ const maxLen = Math.max(oldVal.length, newVal.length);
63
+ for (let i = 0; i < maxLen; i++) {
64
+ const childPath = `${basePath}/${i}`;
65
+ if (i >= oldVal.length) {
66
+ out.push({
67
+ path: childPath,
68
+ description: "Item added",
69
+ severity: "unknown",
70
+ });
71
+ } else if (i >= newVal.length) {
72
+ out.push({
73
+ path: childPath,
74
+ description: "Item removed",
75
+ severity: "unknown",
76
+ });
77
+ } else {
78
+ diffValues(oldVal[i], newVal[i], childPath, out);
79
+ }
80
+ }
81
+ return;
82
+ }
83
+
84
+ // Primitive or mismatched types → treat as value change
85
+ out.push({
86
+ path: basePath,
87
+ description: "Value changed",
88
+ severity: "unknown",
89
+ });
90
+ }
91
+
92
+ function annotateRestChange(change: UniSpecChange): UniSpecChange {
93
+ if (!change.path.startsWith("/service/protocols/rest/paths/")) {
94
+ return change;
95
+ }
96
+
97
+ const segments = change.path.split("/").filter(Boolean);
98
+ // Expected shape: ["service", "protocols", "rest", "paths", pathKey?, method?]
99
+ if (segments[0] !== "service" || segments[1] !== "protocols" || segments[2] !== "rest" || segments[3] !== "paths") {
100
+ return change;
101
+ }
102
+
103
+ const pathKey = segments[4];
104
+ const method = segments[5];
105
+
106
+ const httpMethods = new Set(["get", "head", "options", "post", "put", "patch", "delete"]);
107
+
108
+ const annotated: UniSpecChange = {
109
+ ...change,
110
+ protocol: "rest",
111
+ };
112
+
113
+ if (change.description === "Field removed") {
114
+ if (pathKey && !method) {
115
+ annotated.kind = "rest.path.removed";
116
+ annotated.severity = "breaking";
117
+ } else if (pathKey && method && httpMethods.has(method)) {
118
+ annotated.kind = "rest.operation.removed";
119
+ annotated.severity = "breaking";
120
+ }
121
+ } else if (change.description === "Field added") {
122
+ if (pathKey && !method) {
123
+ annotated.kind = "rest.path.added";
124
+ annotated.severity = "non-breaking";
125
+ } else if (pathKey && method && httpMethods.has(method)) {
126
+ annotated.kind = "rest.operation.added";
127
+ annotated.severity = "non-breaking";
128
+ }
129
+ }
130
+
131
+ return annotated;
132
+ }
133
+
134
+ function annotateWebSocketChange(change: UniSpecChange): UniSpecChange {
135
+ if (!change.path.startsWith("/service/protocols/websocket/channels/")) {
136
+ return change;
137
+ }
138
+
139
+ const segments = change.path.split("/").filter(Boolean);
140
+ // Expected: ["service","protocols","websocket","channels", channelName, ...]
141
+ if (segments[0] !== "service" || segments[1] !== "protocols" || segments[2] !== "websocket" || segments[3] !== "channels") {
142
+ return change;
143
+ }
144
+
145
+ const channelName = segments[4];
146
+ const next = segments[5];
147
+
148
+ const annotated: UniSpecChange = {
149
+ ...change,
150
+ protocol: "websocket",
151
+ };
152
+
153
+ if (!channelName) {
154
+ return annotated;
155
+ }
156
+
157
+ // Channel-level changes
158
+ if (!next) {
159
+ if (change.description === "Field removed") {
160
+ annotated.kind = "websocket.channel.removed";
161
+ annotated.severity = "breaking";
162
+ } else if (change.description === "Field added") {
163
+ annotated.kind = "websocket.channel.added";
164
+ annotated.severity = "non-breaking";
165
+ }
166
+ return annotated;
167
+ }
168
+
169
+ // Message-level changes (channels/{channelName}/messages/{index})
170
+ if (next === "messages") {
171
+ const index = segments[6];
172
+ if (typeof index === "undefined") {
173
+ return annotated;
174
+ }
175
+
176
+ if (change.description === "Item removed") {
177
+ annotated.kind = "websocket.message.removed";
178
+ annotated.severity = "breaking";
179
+ } else if (change.description === "Item added") {
180
+ annotated.kind = "websocket.message.added";
181
+ annotated.severity = "non-breaking";
182
+ }
183
+ }
184
+
185
+ return annotated;
186
+ }
187
+
188
+ function annotateGraphQLChange(change: UniSpecChange): UniSpecChange {
189
+ if (!change.path.startsWith("/service/protocols/graphql/operations/")) {
190
+ return change;
191
+ }
192
+
193
+ const segments = change.path.split("/").filter(Boolean);
194
+ // Expected: ["service","protocols","graphql","operations", kind, opName?]
195
+ if (segments[0] !== "service" || segments[1] !== "protocols" || segments[2] !== "graphql" || segments[3] !== "operations") {
196
+ return change;
197
+ }
198
+
199
+ const opKind = segments[4];
200
+ const opName = segments[5];
201
+
202
+ if (!opKind || !opName) {
203
+ return change;
204
+ }
205
+
206
+ const annotated: UniSpecChange = {
207
+ ...change,
208
+ protocol: "graphql",
209
+ };
210
+
211
+ if (change.description === "Field removed") {
212
+ annotated.kind = "graphql.operation.removed";
213
+ annotated.severity = "breaking";
214
+ } else if (change.description === "Field added") {
215
+ annotated.kind = "graphql.operation.added";
216
+ annotated.severity = "non-breaking";
217
+ }
218
+
219
+ return annotated;
220
+ }
221
+
222
+ /**
223
+ * Compute a structural diff between two UniSpec documents.
224
+ *
225
+ * Current behavior:
226
+ * - Tracks added, removed, and changed fields and array items.
227
+ * - Uses JSON Pointer-like paths rooted at "" (e.g., "/info/title").
228
+ * - Marks all changes with severity "unknown" for now.
229
+ */
230
+ export function diffUniSpec(oldDoc: UniSpecDocument, newDoc: UniSpecDocument): DiffResult {
231
+ const changes: UniSpecChange[] = [];
232
+ diffValues(oldDoc, newDoc, "", changes);
233
+ const annotated = changes.map((change) => annotateWebSocketChange(annotateGraphQLChange(annotateRestChange(change))));
234
+ return { changes: annotated };
235
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./types/index.js";
2
+ export * from "./loader/index.js";
3
+ export * from "./validator/index.js";
4
+ export * from "./normalizer/index.js";
5
+ export * from "./diff/index.js";
6
+ export * from "./converters/index.js";
@@ -0,0 +1,25 @@
1
+ import { UniSpecDocument } from "../types";
2
+
3
+ export interface LoadOptions {
4
+ filename?: string;
5
+ }
6
+
7
+ /**
8
+ * Load a UniSpec document from a raw input value.
9
+ * Currently supports:
10
+ * - JavaScript objects (treated as already parsed UniSpec)
11
+ * - JSON strings
12
+ *
13
+ * YAML and filesystem helpers will be added later, keeping this API stable.
14
+ */
15
+ export async function loadUniSpec(input: string | object, _options: LoadOptions = {}): Promise<UniSpecDocument> {
16
+ if (typeof input === "string") {
17
+ const trimmed = input.trim();
18
+ if (!trimmed) {
19
+ throw new Error("Cannot load UniSpec: input string is empty");
20
+ }
21
+ // For now we assume JSON; YAML support will be added later.
22
+ return JSON.parse(trimmed) as UniSpecDocument;
23
+ }
24
+ return input as UniSpecDocument;
25
+ }
@@ -0,0 +1,156 @@
1
+ import { UniSpecDocument, UniSpecWebSocketProtocol, UniSpecWebSocketChannel, UniSpecWebSocketMessage } from "../types";
2
+
3
+ export interface NormalizeOptions {
4
+ // Placeholder for future normalization options
5
+ }
6
+
7
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
8
+ return Object.prototype.toString.call(value) === "[object Object]";
9
+ }
10
+
11
+ function normalizeValue(value: unknown): unknown {
12
+ if (Array.isArray(value)) {
13
+ return value.map((item) => normalizeValue(item));
14
+ }
15
+
16
+ if (isPlainObject(value)) {
17
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
18
+ const normalized: Record<string, unknown> = {};
19
+ for (const [key, val] of entries) {
20
+ normalized[key] = normalizeValue(val);
21
+ }
22
+ return normalized;
23
+ }
24
+
25
+ return value;
26
+ }
27
+
28
+ function normalizeRestPaths(doc: UniSpecDocument): UniSpecDocument {
29
+ if (!doc || !doc.service || !doc.service.protocols) {
30
+ return doc;
31
+ }
32
+
33
+ const protocols: any = doc.service.protocols;
34
+ const rest: any = protocols.rest;
35
+
36
+ if (!rest || !rest.paths || typeof rest.paths !== "object") {
37
+ return doc;
38
+ }
39
+
40
+ const httpMethodOrder = ["get", "head", "options", "post", "put", "patch", "delete"];
41
+
42
+ const normalizedPaths: Record<string, unknown> = {};
43
+
44
+ for (const path of Object.keys(rest.paths).sort()) {
45
+ const pathItem = (rest.paths as any)[path];
46
+
47
+ if (!pathItem || typeof pathItem !== "object") {
48
+ normalizedPaths[path] = pathItem;
49
+ continue;
50
+ }
51
+
52
+ const pathItemObj: Record<string, unknown> = pathItem as Record<string, unknown>;
53
+
54
+ const ordered: Record<string, unknown> = {};
55
+
56
+ for (const method of httpMethodOrder) {
57
+ if (Object.prototype.hasOwnProperty.call(pathItemObj, method)) {
58
+ ordered[method] = pathItemObj[method];
59
+ }
60
+ }
61
+
62
+ const remainingKeys = Object.keys(pathItemObj).filter((k) => !httpMethodOrder.includes(k)).sort();
63
+ for (const key of remainingKeys) {
64
+ ordered[key] = pathItemObj[key];
65
+ }
66
+
67
+ normalizedPaths[path] = ordered;
68
+ }
69
+
70
+ rest.paths = normalizedPaths;
71
+
72
+ return doc;
73
+ }
74
+
75
+ function normalizeWebSocket(doc: UniSpecDocument): UniSpecDocument {
76
+ if (!doc || !doc.service || !doc.service.protocols) {
77
+ return doc;
78
+ }
79
+
80
+ const protocols: any = doc.service.protocols;
81
+ const websocket: UniSpecWebSocketProtocol | undefined = protocols.websocket;
82
+
83
+ if (!websocket || !websocket.channels || typeof websocket.channels !== "object") {
84
+ return doc;
85
+ }
86
+
87
+ const originalChannels = websocket.channels as Record<string, UniSpecWebSocketChannel>;
88
+ const sortedChannels: Record<string, UniSpecWebSocketChannel> = {};
89
+
90
+ for (const name of Object.keys(originalChannels).sort()) {
91
+ const channel = originalChannels[name];
92
+ if (!channel) {
93
+ continue;
94
+ }
95
+
96
+ let messages = channel.messages;
97
+ if (Array.isArray(messages)) {
98
+ messages = [...messages].sort((a: UniSpecWebSocketMessage, b: UniSpecWebSocketMessage) => {
99
+ const aName = a?.name ?? "";
100
+ const bName = b?.name ?? "";
101
+ return aName.localeCompare(bName);
102
+ });
103
+ }
104
+
105
+ sortedChannels[name] = {
106
+ ...channel,
107
+ ...(messages ? { messages } : {}),
108
+ };
109
+ }
110
+
111
+ websocket.channels = sortedChannels;
112
+
113
+ return doc;
114
+ }
115
+
116
+ function normalizeGraphqlOperations(doc: UniSpecDocument): UniSpecDocument {
117
+ if (!doc || !doc.service || !doc.service.protocols) {
118
+ return doc;
119
+ }
120
+
121
+ const protocols: any = doc.service.protocols;
122
+ const graphql: any = protocols.graphql;
123
+
124
+ if (!graphql || !graphql.operations) {
125
+ return doc;
126
+ }
127
+
128
+ const kinds = ["queries", "mutations", "subscriptions"] as const;
129
+
130
+ for (const kind of kinds) {
131
+ const bucket = graphql.operations[kind];
132
+ if (!bucket || typeof bucket !== "object") {
133
+ continue;
134
+ }
135
+
136
+ const sorted: Record<string, unknown> = {};
137
+ for (const name of Object.keys(bucket).sort()) {
138
+ sorted[name] = bucket[name];
139
+ }
140
+ graphql.operations[kind] = sorted;
141
+ }
142
+
143
+ return doc;
144
+ }
145
+
146
+ /**
147
+ * Normalize a UniSpec document into a canonical, deterministic form.
148
+ *
149
+ * Current behavior:
150
+ * - Recursively sorts object keys lexicographically.
151
+ * - Preserves values as-is.
152
+ */
153
+ export function normalizeUniSpec(doc: UniSpecDocument, _options: NormalizeOptions = {}): UniSpecDocument {
154
+ const normalized = normalizeValue(doc) as UniSpecDocument;
155
+ return normalizeWebSocket(normalizeGraphqlOperations(normalizeRestPaths(normalized)));
156
+ }
@@ -0,0 +1,67 @@
1
+ export interface UniSpecGraphQLSchema {
2
+ sdl?: string;
3
+ }
4
+
5
+ export interface UniSpecGraphQLOperations {
6
+ queries?: Record<string, unknown>;
7
+ mutations?: Record<string, unknown>;
8
+ subscriptions?: Record<string, unknown>;
9
+ }
10
+
11
+ export interface UniSpecGraphQLProtocol {
12
+ schema?: UniSpecGraphQLSchema;
13
+ operations?: UniSpecGraphQLOperations;
14
+ extensions?: Record<string, unknown>;
15
+ }
16
+
17
+ export interface UniSpecWebSocketMessage {
18
+ name?: string;
19
+ summary?: string;
20
+ description?: string;
21
+ payload?: unknown;
22
+ extensions?: Record<string, unknown>;
23
+ }
24
+
25
+ export interface UniSpecWebSocketChannel {
26
+ summary?: string;
27
+ title?: string;
28
+ description?: string;
29
+ direction?: string;
30
+ messages?: UniSpecWebSocketMessage[];
31
+ extensions?: Record<string, unknown>;
32
+ }
33
+
34
+ export interface UniSpecWebSocketProtocol {
35
+ channels?: Record<string, UniSpecWebSocketChannel>;
36
+ extensions?: Record<string, unknown>;
37
+ }
38
+
39
+ export interface UniSpecServiceProtocols {
40
+ rest?: unknown;
41
+ graphql?: UniSpecGraphQLProtocol;
42
+ websocket?: UniSpecWebSocketProtocol;
43
+ }
44
+
45
+ export interface UniSpecService {
46
+ name: string;
47
+ title?: string;
48
+ description?: string;
49
+ protocols?: UniSpecServiceProtocols;
50
+ }
51
+
52
+ export interface UniSpecDocument {
53
+ unispecVersion: string;
54
+ service: UniSpecService;
55
+ extensions?: Record<string, unknown>;
56
+ }
57
+
58
+ export interface ValidationError {
59
+ message: string;
60
+ path?: string;
61
+ code?: string;
62
+ }
63
+
64
+ export interface ValidationResult {
65
+ valid: boolean;
66
+ errors: ValidationError[];
67
+ }
@@ -0,0 +1,61 @@
1
+ import Ajv2020, { ErrorObject } from "ajv/dist/2020.js";
2
+ import { createRequire } from "module";
3
+ import { unispec as unispecSchema, manifest as unispecManifest } from "@unispechq/unispec-schema";
4
+ import { UniSpecDocument, ValidationResult } from "../types";
5
+
6
+ export interface ValidateOptions {
7
+ // Placeholder for future validation options (e.g., strict mode, schema version)
8
+ }
9
+
10
+ const require = createRequire(import.meta.url);
11
+
12
+ const ajv = new Ajv2020({
13
+ allErrors: true,
14
+ strict: true,
15
+ });
16
+
17
+ // Register all UniSpec subschemas so that Ajv can resolve internal $ref links
18
+ try {
19
+ const schemaRootPath = require.resolve("@unispechq/unispec-schema");
20
+ const schemaDir = schemaRootPath.replace(/index\.(cjs|mjs|js)$/u, "schema/");
21
+
22
+ const types = (unispecManifest as any)?.types ?? {};
23
+ const typeSchemaPaths: string[] = Object.values(types).map((rel: unknown) => String(rel));
24
+
25
+ const loadedTypeSchemas = typeSchemaPaths.map((relPath) => require(schemaDir + relPath));
26
+
27
+ ajv.addSchema(loadedTypeSchemas as object | object[]);
28
+ } catch {
29
+ // If subschemas cannot be loaded for some reason, validation will still work for
30
+ // parts of the schema that do not rely on those $ref references.
31
+ }
32
+
33
+ const validateFn = ajv.compile(unispecSchema as object);
34
+
35
+ function mapAjvErrors(errors: ErrorObject[] | null | undefined): ValidationResult["errors"] {
36
+ if (!errors) return [];
37
+ return errors.map((error) => ({
38
+ message: error.message || "UniSpec validation error",
39
+ path: error.instancePath || error.schemaPath,
40
+ code: error.keyword,
41
+ }));
42
+ }
43
+
44
+ /**
45
+ * Validate a UniSpec document against the UniSpec JSON Schema.
46
+ */
47
+ export async function validateUniSpec(doc: UniSpecDocument, _options: ValidateOptions = {}): Promise<ValidationResult> {
48
+ const valid = validateFn(doc);
49
+
50
+ if (valid) {
51
+ return {
52
+ valid: true,
53
+ errors: [],
54
+ };
55
+ }
56
+
57
+ return {
58
+ valid: false,
59
+ errors: mapAjvErrors(validateFn.errors),
60
+ };
61
+ }
@@ -0,0 +1,126 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+
4
+ import * as core from "../dist/index.js";
5
+
6
+ const { toOpenAPI, toGraphQLSDL, toWebSocketModel } = core;
7
+
8
+ test("toOpenAPI produces basic OpenAPI structure from UniSpec document", () => {
9
+ const doc = {
10
+ unispecVersion: "0.1.0",
11
+ service: {
12
+ name: "test-service",
13
+ title: "Service",
14
+ description: "Desc",
15
+ protocols: {
16
+ rest: {
17
+ servers: [{ url: "https://api.example.com" }],
18
+ paths: {
19
+ "/ping": {
20
+ get: {},
21
+ },
22
+ },
23
+ components: {
24
+ schemas: {
25
+ PingResponse: {
26
+ type: "object",
27
+ },
28
+ },
29
+ },
30
+ security: [{ bearerAuth: [] }],
31
+ tags: [
32
+ {
33
+ name: "ping",
34
+ description: "Ping operations",
35
+ },
36
+ ],
37
+ "x-extra-rest-field": true,
38
+ },
39
+ },
40
+ },
41
+ };
42
+
43
+ const openapi = toOpenAPI(doc);
44
+
45
+ assert.equal(openapi.openapi, "3.1.0");
46
+ assert.equal(openapi.info.title, "Service");
47
+ assert.equal(openapi.info.description, "Desc");
48
+ assert.ok(openapi.paths["/ping"]);
49
+ assert.ok(openapi.components);
50
+ assert.ok(openapi.components.schemas.PingResponse);
51
+ assert.ok(Array.isArray(openapi.security));
52
+ assert.ok(Array.isArray(openapi.tags));
53
+ assert.equal(openapi["x-extra-rest-field"], true);
54
+ });
55
+
56
+ test("toGraphQLSDL returns SDL string wrapper", () => {
57
+ const doc = {
58
+ unispecVersion: "0.1.0",
59
+ service: {
60
+ name: "test-service",
61
+ title: "GraphQL Service",
62
+ description: "GraphQL description",
63
+ protocols: {
64
+ graphql: {
65
+ schema: {
66
+ sdl: "type Query { hello: String! }",
67
+ },
68
+ },
69
+ },
70
+ },
71
+ };
72
+
73
+ const result = toGraphQLSDL(doc);
74
+
75
+ assert.equal(typeof result, "object");
76
+ assert.equal(typeof result.sdl, "string");
77
+ assert.equal(result.sdl, "type Query { hello: String! }");
78
+ });
79
+
80
+ test("toWebSocketModel returns WS model wrapper", () => {
81
+ const doc = {
82
+ unispecVersion: "0.1.0",
83
+ service: {
84
+ name: "test-service",
85
+ title: "WS Service",
86
+ description: "WebSocket description",
87
+ protocols: {
88
+ websocket: {
89
+ channels: {
90
+ ping: {
91
+ summary: "Ping channel",
92
+ description: "Ping messages",
93
+ direction: "bidirectional",
94
+ messages: [
95
+ {
96
+ name: "ping",
97
+ summary: "Ping message",
98
+ },
99
+ ],
100
+ },
101
+ },
102
+ },
103
+ },
104
+ },
105
+ };
106
+
107
+ const model = toWebSocketModel(doc);
108
+
109
+ assert.equal(typeof model, "object");
110
+ assert.ok(model["x-unispec-ws"]);
111
+ assert.deepEqual(model.service, {
112
+ name: "test-service",
113
+ title: "WS Service",
114
+ description: "WebSocket description",
115
+ });
116
+ assert.ok(Array.isArray(model.channels));
117
+ assert.equal(model.channels.length, 1);
118
+ assert.equal(model.channels[0].name, "ping");
119
+ assert.equal(model.channels[0].summary, "Ping channel");
120
+ assert.equal(model.channels[0].description, "Ping messages");
121
+ assert.equal(model.channels[0].direction, "bidirectional");
122
+ assert.ok(Array.isArray(model.channels[0].messages));
123
+ assert.equal(model.channels[0].messages[0].name, "ping");
124
+ assert.equal(model.channels[0].messages[0].summary, "Ping message");
125
+ assert.ok(model.rawProtocol);
126
+ });