@elliots/typical-compiler 0.2.3 → 0.2.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elliot Shepherd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ProjectHandle, TransformResult } from './types.js';
1
+ import type { ProjectHandle, TransformResult, AnalyseResult } from "./types.js";
2
2
  export interface TypicalCompilerOptions {
3
3
  /** Path to the typical binary. If not provided, uses the bundled binary. */
4
4
  binaryPath?: string;
@@ -16,8 +16,20 @@ export declare class TypicalCompiler {
16
16
  start(): Promise<void>;
17
17
  close(): Promise<void>;
18
18
  loadProject(configFileName: string): Promise<ProjectHandle>;
19
- transformFile(project: ProjectHandle | string, fileName: string, ignoreTypes?: string[], maxGeneratedFunctions?: number, reusableValidators?: 'auto' | 'never' | 'always'): Promise<TransformResult>;
19
+ transformFile(project: ProjectHandle | string, fileName: string, ignoreTypes?: string[], maxGeneratedFunctions?: number): Promise<TransformResult>;
20
20
  release(handle: ProjectHandle | string): Promise<void>;
21
+ /**
22
+ * Analyse a file for validation points without transforming it.
23
+ * Returns information about which parameters, returns, and casts will be validated.
24
+ * Used by the VSCode extension to show validation indicators.
25
+ *
26
+ * @param project - Project handle or ID
27
+ * @param fileName - Path to the file to analyse
28
+ * @param content - Optional file content for live updates (uses disk version if not provided)
29
+ * @param ignoreTypes - Optional glob patterns for types to skip
30
+ * @returns Analysis result with validation items
31
+ */
32
+ analyseFile(project: ProjectHandle | string, fileName: string, content?: string, ignoreTypes?: string[]): Promise<AnalyseResult>;
21
33
  /**
22
34
  * Transform a standalone TypeScript source string.
23
35
  * Creates a temporary project to enable type checking.
@@ -30,7 +42,6 @@ export declare class TypicalCompiler {
30
42
  transformSource(fileName: string, source: string, options?: {
31
43
  ignoreTypes?: string[];
32
44
  maxGeneratedFunctions?: number;
33
- reusableValidators?: 'auto' | 'never' | 'always';
34
45
  }): Promise<TransformResult>;
35
46
  private request;
36
47
  private handleData;
package/dist/client.js CHANGED
@@ -1,28 +1,25 @@
1
- import { spawn } from 'node:child_process';
2
- import { join, dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { createRequire } from 'node:module';
5
- import { encodeRequest, decodeResponse } from './protocol.js';
1
+ import { spawn } from "node:child_process";
2
+ import { join, dirname } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createRequire } from "node:module";
5
+ import { encodeRequest, decodeResponse } from "./protocol.js";
6
+ import { existsSync } from "node:fs";
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
7
8
  const require = createRequire(import.meta.url);
8
- const debug = process.env.DEBUG === '1';
9
+ const debug = process.env.DEBUG === "1";
9
10
  function debugLog(...args) {
10
11
  if (debug) {
11
12
  console.error(...args);
12
13
  }
13
14
  }
14
15
  function getBinaryPath() {
15
- // try local binary first (for development)
16
- const localBinPath = join(__dirname, '..', 'bin', 'typical');
17
- try {
18
- require('fs').accessSync(localBinPath);
19
- debugLog(`[CLIENT] Using local binary at ${localBinPath}`);
20
- return localBinPath;
16
+ // use bin/typical in development
17
+ const devPath = join(__dirname, "../bin/typical");
18
+ if (existsSync(devPath)) {
19
+ debugLog(`[CLIENT] Using development binary at ${devPath}`);
20
+ return devPath;
21
21
  }
22
- catch {
23
- // continue to platform-specific package
24
- }
25
- // Then use platform-specific package
22
+ // Find platform-specific package
26
23
  const platform = process.platform; // darwin, linux, win32
27
24
  const arch = process.arch; // arm64, x64
28
25
  const pkgName = `@elliots/typical-compiler-${platform}-${arch}`;
@@ -43,20 +40,20 @@ export class TypicalCompiler {
43
40
  }
44
41
  async start() {
45
42
  if (this.process) {
46
- throw new Error('Compiler already started');
43
+ throw new Error("Compiler already started");
47
44
  }
48
- this.process = spawn(this.binaryPath, ['--cwd', this.cwd], {
49
- stdio: ['pipe', 'pipe', 'inherit'],
45
+ this.process = spawn(this.binaryPath, ["--cwd", this.cwd], {
46
+ stdio: ["pipe", "pipe", "inherit"],
50
47
  });
51
48
  // Don't let the child process keep the Node process alive
52
49
  this.process.unref();
53
- this.process.stdout.on('data', (data) => {
50
+ this.process.stdout.on("data", (data) => {
54
51
  this.handleData(data);
55
52
  });
56
- this.process.on('error', err => {
57
- console.error('Compiler process error:', err);
53
+ this.process.on("error", (err) => {
54
+ console.error("Compiler process error:", err);
58
55
  });
59
- this.process.on('exit', code => {
56
+ this.process.on("exit", (code) => {
60
57
  this.process = null;
61
58
  // Reject any pending requests
62
59
  for (const [, { reject }] of this.pendingRequests) {
@@ -65,8 +62,8 @@ export class TypicalCompiler {
65
62
  this.pendingRequests.clear();
66
63
  });
67
64
  // Test the connection with echo
68
- const result = await this.request('echo', 'ping');
69
- if (result !== 'ping') {
65
+ const result = await this.request("echo", "ping");
66
+ if (result !== "ping") {
70
67
  throw new Error(`Echo test failed: expected "ping", got "${result}"`);
71
68
  }
72
69
  }
@@ -81,21 +78,40 @@ export class TypicalCompiler {
81
78
  }
82
79
  }
83
80
  async loadProject(configFileName) {
84
- return this.request('loadProject', { configFileName });
81
+ return this.request("loadProject", { configFileName });
85
82
  }
86
- async transformFile(project, fileName, ignoreTypes, maxGeneratedFunctions, reusableValidators) {
87
- const projectId = typeof project === 'string' ? project : project.id;
88
- return this.request('transformFile', {
83
+ async transformFile(project, fileName, ignoreTypes, maxGeneratedFunctions) {
84
+ const projectId = typeof project === "string" ? project : project.id;
85
+ return this.request("transformFile", {
89
86
  project: projectId,
90
87
  fileName,
91
88
  ignoreTypes,
92
89
  maxGeneratedFunctions,
93
- reusableValidators,
94
90
  });
95
91
  }
96
92
  async release(handle) {
97
- const id = typeof handle === 'string' ? handle : handle.id;
98
- await this.request('release', id);
93
+ const id = typeof handle === "string" ? handle : handle.id;
94
+ await this.request("release", id);
95
+ }
96
+ /**
97
+ * Analyse a file for validation points without transforming it.
98
+ * Returns information about which parameters, returns, and casts will be validated.
99
+ * Used by the VSCode extension to show validation indicators.
100
+ *
101
+ * @param project - Project handle or ID
102
+ * @param fileName - Path to the file to analyse
103
+ * @param content - Optional file content for live updates (uses disk version if not provided)
104
+ * @param ignoreTypes - Optional glob patterns for types to skip
105
+ * @returns Analysis result with validation items
106
+ */
107
+ async analyseFile(project, fileName, content, ignoreTypes) {
108
+ const projectId = typeof project === "string" ? project : project.id;
109
+ return this.request("analyseFile", {
110
+ project: projectId,
111
+ fileName,
112
+ content,
113
+ ignoreTypes,
114
+ });
99
115
  }
100
116
  /**
101
117
  * Transform a standalone TypeScript source string.
@@ -107,17 +123,16 @@ export class TypicalCompiler {
107
123
  * @returns Transformed code with validation
108
124
  */
109
125
  async transformSource(fileName, source, options) {
110
- return this.request('transformSource', {
126
+ return this.request("transformSource", {
111
127
  fileName,
112
128
  source,
113
129
  ignoreTypes: options?.ignoreTypes,
114
130
  maxGeneratedFunctions: options?.maxGeneratedFunctions,
115
- reusableValidators: options?.reusableValidators,
116
131
  });
117
132
  }
118
133
  async request(method, payload) {
119
134
  if (!this.process) {
120
- throw new Error('Compiler not started');
135
+ throw new Error("Compiler not started");
121
136
  }
122
137
  // Use unique request ID to correlate request/response
123
138
  const requestId = `${method}:${this.nextRequestId++}`;
@@ -143,17 +158,18 @@ export class TypicalCompiler {
143
158
  // Find the pending request
144
159
  const pending = this.pendingRequests.get(method);
145
160
  if (!pending) {
146
- const pendingKeys = [...this.pendingRequests.keys()].join(', ') || '(none)';
147
- throw new Error(`No pending request for method: ${method}. Pending requests: ${pendingKeys}. ` + `This indicates a protocol bug - received response for a request that wasn't made or was already resolved.`);
161
+ const pendingKeys = [...this.pendingRequests.keys()].join(", ") || "(none)";
162
+ throw new Error(`No pending request for method: ${method}. Pending requests: ${pendingKeys}. ` +
163
+ `This indicates a protocol bug - received response for a request that wasn't made or was already resolved.`);
148
164
  }
149
165
  this.pendingRequests.delete(method);
150
166
  if (messageType === 4 /* MessageType.Response */) {
151
167
  // Parse JSON payload
152
- const result = payload.length > 0 ? JSON.parse(payload.toString('utf8')) : null;
168
+ const result = payload.length > 0 ? JSON.parse(payload.toString("utf8")) : null;
153
169
  pending.resolve(result);
154
170
  }
155
171
  else if (messageType === 5 /* MessageType.Error */) {
156
- pending.reject(new Error(payload.toString('utf8')));
172
+ pending.reject(new Error(payload.toString("utf8")));
157
173
  }
158
174
  else {
159
175
  pending.reject(new Error(`Unexpected message type: ${messageType}`));
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { TypicalCompiler, type TypicalCompilerOptions } from './client.js';
2
- export type { ProjectHandle, TransformResult, RawSourceMap } from './types.js';
1
+ export { TypicalCompiler, type TypicalCompilerOptions } from "./client.js";
2
+ export type { ProjectHandle, TransformResult, RawSourceMap } from "./types.js";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { TypicalCompiler } from './client.js';
1
+ export { TypicalCompiler } from "./client.js";
package/dist/protocol.js CHANGED
@@ -8,9 +8,9 @@ const MessagePackTypeBin16 = 0xc5;
8
8
  const MessagePackTypeBin32 = 0xc6;
9
9
  const MessagePackTypeU8 = 0xcc;
10
10
  export function encodeRequest(method, payload) {
11
- const methodBuf = Buffer.from(method, 'utf8');
11
+ const methodBuf = Buffer.from(method, "utf8");
12
12
  const payloadStr = JSON.stringify(payload);
13
- const payloadBuf = Buffer.from(payloadStr, 'utf8');
13
+ const payloadBuf = Buffer.from(payloadStr, "utf8");
14
14
  // Calculate total size
15
15
  // 1 byte for array marker (0x93)
16
16
  // 2 bytes for message type (0xCC + type)
@@ -36,7 +36,7 @@ export function decodeResponse(data) {
36
36
  let offset = 0;
37
37
  // Check array marker
38
38
  if (data[offset++] !== MessagePackTypeFixedArray3) {
39
- throw new Error(`Expected 0x93, got 0x${data[0].toString(16)}: first 200 of data: ${data.subarray(0, 200).toString('utf8')}`);
39
+ throw new Error(`Expected 0x93, got 0x${data[0].toString(16)}: first 200 of data: ${data.subarray(0, 200).toString("utf8")}`);
40
40
  }
41
41
  // Read message type
42
42
  if (data[offset++] !== MessagePackTypeU8) {
@@ -46,7 +46,7 @@ export function decodeResponse(data) {
46
46
  // Read method
47
47
  const { value: methodBuf, newOffset: offset2 } = readBin(data, offset);
48
48
  offset = offset2;
49
- const method = methodBuf.toString('utf8');
49
+ const method = methodBuf.toString("utf8");
50
50
  // Read payload
51
51
  const { value: payload, newOffset: offset3 } = readBin(data, offset);
52
52
  return { messageType, method, payload, bytesConsumed: offset3 };
@@ -79,25 +79,25 @@ function writeBin(buf, offset, data) {
79
79
  }
80
80
  function readBin(buf, offset) {
81
81
  if (offset >= buf.length) {
82
- throw new Error('Not enough data: need type byte');
82
+ throw new Error("Not enough data: need type byte");
83
83
  }
84
84
  const type = buf[offset++];
85
85
  let length;
86
86
  switch (type) {
87
87
  case MessagePackTypeBin8:
88
88
  if (offset >= buf.length)
89
- throw new Error('Not enough data: need length byte');
89
+ throw new Error("Not enough data: need length byte");
90
90
  length = buf[offset++];
91
91
  break;
92
92
  case MessagePackTypeBin16:
93
93
  if (offset + 2 > buf.length)
94
- throw new Error('Not enough data: need 2 length bytes');
94
+ throw new Error("Not enough data: need 2 length bytes");
95
95
  length = buf.readUInt16BE(offset);
96
96
  offset += 2;
97
97
  break;
98
98
  case MessagePackTypeBin32:
99
99
  if (offset + 4 > buf.length)
100
- throw new Error('Not enough data: need 4 length bytes');
100
+ throw new Error("Not enough data: need 4 length bytes");
101
101
  length = buf.readUInt32BE(offset);
102
102
  offset += 4;
103
103
  break;
package/dist/types.d.ts CHANGED
@@ -16,3 +16,27 @@ export interface TransformResult {
16
16
  code: string;
17
17
  sourceMap?: RawSourceMap;
18
18
  }
19
+ /** Represents a single validation point in the source code */
20
+ export interface ValidationItem {
21
+ /** 1-based line number */
22
+ startLine: number;
23
+ /** 0-based column */
24
+ startColumn: number;
25
+ /** 1-based line number */
26
+ endLine: number;
27
+ /** 0-based column */
28
+ endColumn: number;
29
+ /** Type of validation: "parameter", "return", "cast", "json-parse", "json-stringify" */
30
+ kind: "parameter" | "return" | "cast" | "json-parse" | "json-stringify";
31
+ /** Name of the item being validated (param name, "return value", or expression text) */
32
+ name: string;
33
+ /** Whether the item will be validated or skipped */
34
+ status: "validated" | "skipped";
35
+ /** Human-readable type string */
36
+ typeString: string;
37
+ /** Reason for skipping (when status is "skipped") */
38
+ skipReason?: string;
39
+ }
40
+ export interface AnalyseResult {
41
+ items: ValidationItem[];
42
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elliots/typical-compiler",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "TypeScript compiler powered by tsgo for typical validation",
5
5
  "keywords": [
6
6
  "compiler",
@@ -26,16 +26,16 @@
26
26
  "typescript": "^5.7.0"
27
27
  },
28
28
  "optionalDependencies": {
29
- "@elliots/typical-compiler-darwin-arm64": "0.2.3",
30
- "@elliots/typical-compiler-darwin-x64": "0.2.3",
31
- "@elliots/typical-compiler-linux-arm64": "0.2.3",
32
- "@elliots/typical-compiler-linux-x64": "0.2.3",
33
- "@elliots/typical-compiler-win32-arm64": "0.2.3",
34
- "@elliots/typical-compiler-win32-x64": "0.2.3"
29
+ "@elliots/typical-compiler-darwin-arm64": "0.2.5",
30
+ "@elliots/typical-compiler-darwin-x64": "0.2.5",
31
+ "@elliots/typical-compiler-linux-arm64": "0.2.5",
32
+ "@elliots/typical-compiler-linux-x64": "0.2.5",
33
+ "@elliots/typical-compiler-win32-arm64": "0.2.5",
34
+ "@elliots/typical-compiler-win32-x64": "0.2.5"
35
35
  },
36
36
  "scripts": {
37
- "build": "tsc",
38
- "build:go": "./go/scripts/sync-shims.sh && cd go && go build -o ../bin/typical ./cmd/typical",
39
- "test": "npx tsx test/e2e.ts"
37
+ "build": "npm run build:ts && npm run build:go",
38
+ "build:ts": "tsc",
39
+ "build:go": "./go/scripts/sync-shims.sh && cd go && go build -o ../bin/typical ./cmd/typical"
40
40
  }
41
41
  }