@c7-digital/ledger 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/BUILD.md +125 -0
  2. package/LICENSE +17 -0
  3. package/README.md +97 -0
  4. package/lib/scripts/build.d.ts +9 -0
  5. package/lib/scripts/build.js +366 -0
  6. package/lib/scripts/enhance-types.d.ts +3 -0
  7. package/lib/scripts/enhance-types.js +174 -0
  8. package/lib/scripts/generate-asyncapi-types.d.ts +9 -0
  9. package/lib/scripts/generate-asyncapi-types.js +129 -0
  10. package/lib/scripts/generate-schema-modules.d.ts +3 -0
  11. package/lib/scripts/generate-schema-modules.js +33 -0
  12. package/lib/src/TemplateEmitterMap.d.ts +40 -0
  13. package/lib/src/TemplateEmitterMap.js +57 -0
  14. package/lib/src/client.d.ts +55 -0
  15. package/lib/src/client.js +62 -0
  16. package/lib/src/generated/api.d.ts +7147 -0
  17. package/lib/src/generated/api.js +1 -0
  18. package/lib/src/generated/async-api.d.ts +1665 -0
  19. package/lib/src/generated/async-api.js +1 -0
  20. package/lib/src/generated/asyncapi-schema.d.ts +1 -0
  21. package/lib/src/generated/asyncapi-schema.js +2233 -0
  22. package/lib/src/generated/openapi-schema.d.ts +1 -0
  23. package/lib/src/generated/openapi-schema.js +7321 -0
  24. package/lib/src/generated/sdk-version.d.ts +1 -0
  25. package/lib/src/generated/sdk-version.js +3 -0
  26. package/lib/src/index.d.ts +8 -0
  27. package/lib/src/index.js +8 -0
  28. package/lib/src/ledger.d.ts +188 -0
  29. package/lib/src/ledger.js +849 -0
  30. package/lib/src/ledger.test.d.ts +1 -0
  31. package/lib/src/ledger.test.js +23 -0
  32. package/lib/src/logger.d.ts +41 -0
  33. package/lib/src/logger.js +56 -0
  34. package/lib/src/multistream.d.ts +47 -0
  35. package/lib/src/multistream.js +123 -0
  36. package/lib/src/translate.d.ts +5 -0
  37. package/lib/src/translate.js +30 -0
  38. package/lib/src/types.d.ts +201 -0
  39. package/lib/src/types.js +1 -0
  40. package/lib/src/util.d.ts +3 -0
  41. package/lib/src/util.js +7 -0
  42. package/lib/src/validation.d.ts +27 -0
  43. package/lib/src/validation.js +182 -0
  44. package/lib/src/valueTypes.d.ts +34 -0
  45. package/lib/src/valueTypes.js +76 -0
  46. package/lib/src/websocket.d.ts +69 -0
  47. package/lib/src/websocket.js +125 -0
  48. package/lib/tsconfig.tsbuildinfo +1 -0
  49. package/lib-lite/scripts/build.d.ts +9 -0
  50. package/lib-lite/scripts/build.js +366 -0
  51. package/lib-lite/scripts/enhance-types.d.ts +3 -0
  52. package/lib-lite/scripts/enhance-types.js +174 -0
  53. package/lib-lite/scripts/generate-asyncapi-types.d.ts +9 -0
  54. package/lib-lite/scripts/generate-asyncapi-types.js +129 -0
  55. package/lib-lite/scripts/generate-schema-modules.d.ts +3 -0
  56. package/lib-lite/scripts/generate-schema-modules.js +33 -0
  57. package/lib-lite/src/TemplateEmitterMap.d.ts +40 -0
  58. package/lib-lite/src/TemplateEmitterMap.js +57 -0
  59. package/lib-lite/src/client.d.ts +55 -0
  60. package/lib-lite/src/client.js +62 -0
  61. package/lib-lite/src/generated/api.d.ts +7147 -0
  62. package/lib-lite/src/generated/api.js +1 -0
  63. package/lib-lite/src/generated/async-api.d.ts +1665 -0
  64. package/lib-lite/src/generated/async-api.js +1 -0
  65. package/lib-lite/src/generated/asyncapi-schema.d.ts +1 -0
  66. package/lib-lite/src/generated/asyncapi-schema.js +2 -0
  67. package/lib-lite/src/generated/openapi-schema.d.ts +1 -0
  68. package/lib-lite/src/generated/openapi-schema.js +2 -0
  69. package/lib-lite/src/generated/sdk-version.d.ts +1 -0
  70. package/lib-lite/src/generated/sdk-version.js +3 -0
  71. package/lib-lite/src/index.d.ts +8 -0
  72. package/lib-lite/src/index.js +8 -0
  73. package/lib-lite/src/ledger.d.ts +188 -0
  74. package/lib-lite/src/ledger.js +849 -0
  75. package/lib-lite/src/ledger.test.d.ts +1 -0
  76. package/lib-lite/src/ledger.test.js +23 -0
  77. package/lib-lite/src/logger.d.ts +41 -0
  78. package/lib-lite/src/logger.js +56 -0
  79. package/lib-lite/src/multistream.d.ts +47 -0
  80. package/lib-lite/src/multistream.js +123 -0
  81. package/lib-lite/src/translate.d.ts +5 -0
  82. package/lib-lite/src/translate.js +30 -0
  83. package/lib-lite/src/types.d.ts +201 -0
  84. package/lib-lite/src/types.js +1 -0
  85. package/lib-lite/src/util.d.ts +3 -0
  86. package/lib-lite/src/util.js +7 -0
  87. package/lib-lite/src/validation.d.ts +14 -0
  88. package/lib-lite/src/validation.js +31 -0
  89. package/lib-lite/src/valueTypes.d.ts +34 -0
  90. package/lib-lite/src/valueTypes.js +76 -0
  91. package/lib-lite/src/websocket.d.ts +69 -0
  92. package/lib-lite/src/websocket.js +125 -0
  93. package/lib-lite/tsconfig.temp.tsbuildinfo +1 -0
  94. package/package.json +72 -0
  95. package/scripts/build.ts +456 -0
  96. package/scripts/enhance-types.ts +223 -0
  97. package/scripts/generate-asyncapi-types.ts +158 -0
  98. package/scripts/generate-schema-modules.ts +52 -0
package/BUILD.md ADDED
@@ -0,0 +1,125 @@
1
+ # Ledger Build
2
+
3
+ A standalone, repeatable build system for generating TypeScript types from OpenAPI and AsyncAPI specifications with value.proto branding.
4
+
5
+ ## Features
6
+
7
+ - **SDK Version Targeting**: Generate types for specific Daml SDK versions
8
+ - **Auto-Discovery**: Automatically find the latest specification files
9
+ - **In-Place Branding**: Apply value.proto constraints to generated types
10
+ - **Parallel Processing**: Optimize build performance with concurrent operations
11
+ - **Schema Embedding**: Include YAML schemas for runtime validation
12
+ - **Portable**: No hardcoded paths, works as standalone package
13
+
14
+ ## Usage
15
+
16
+ ### As NPM Script
17
+
18
+ ```bash
19
+ pnpm build # Use configured SDK version
20
+ pnpm build -- --sdk-version=3.4.0 # Override SDK version
21
+ ```
22
+
23
+ ### As Standalone Binary
24
+
25
+ ```bash
26
+ pnpm exec ledger-build # Auto-discover latest specs
27
+ pnpm exec ledger-build --sdk-version=3.4.0 # Target specific SDK version
28
+ ```
29
+
30
+ ### Programmatic Usage
31
+
32
+ ```typescript
33
+ import { build } from "@c7-digital/ledger/scripts/build";
34
+
35
+ await build();
36
+ ```
37
+
38
+ ## Required Dependencies
39
+
40
+ The build system requires these development dependencies:
41
+
42
+ ```json
43
+ {
44
+ "devDependencies": {
45
+ "openapi-typescript": "^7.4.2",
46
+ "tsc-alias": "^1.8.16",
47
+ "tsx": "^4.11.0",
48
+ "typescript": "^5.8.3",
49
+ "yaml": "^2.8.1"
50
+ }
51
+ }
52
+ ```
53
+
54
+ ## Directory Structure
55
+
56
+ ### Input
57
+
58
+ ```
59
+ specs/
60
+ ├── openapi_{SDK_VERSION}.yaml
61
+ └── asyncapi_{SDK_VERSION}.yaml
62
+ ```
63
+
64
+ ### Output
65
+
66
+ ```
67
+ src/generated/
68
+ ├── api.ts # OpenAPI types (branded)
69
+ ├── async-api.ts # AsyncAPI types (branded)
70
+ ├── asyncapi-schema.ts # Embedded AsyncAPI YAML
71
+ ├── openapi-schema.ts # Embedded OpenAPI YAML
72
+ └── sdk-version.ts # SDK version constant
73
+ ```
74
+
75
+ ## Branding
76
+
77
+ The build system automatically applies value.proto constraints to string fields:
78
+
79
+ - `LedgerString` for contract/update/command IDs
80
+ - `PartyIdString` for party identifiers
81
+ - `UserIdString` for user identifiers
82
+ - `NameString` for choice names
83
+ - `PackageIdString` for template/package identifiers
84
+
85
+ ## Standalone Package Usage
86
+
87
+ To use this build system in other projects:
88
+
89
+ 1. **Install the package**:
90
+
91
+ ```bash
92
+ pnpm install @c7-digital/ledger
93
+ ```
94
+
95
+ 2. **Add to package.json**:
96
+
97
+ ```json
98
+ {
99
+ "scripts": {
100
+ "generate-types": "pnpm exec ledger-build --sdk-version=3.4.0"
101
+ }
102
+ }
103
+ ```
104
+
105
+ 3. **Create spec directory structure**:
106
+
107
+ ```
108
+ specs/
109
+ ├── openapi_3.4.0.yaml
110
+ └── asyncapi_3.4.0.yaml
111
+ ```
112
+
113
+ 4. **Run the build**:
114
+ ```bash
115
+ pnpm run generate-types
116
+ ```
117
+
118
+ ## Environment Variables
119
+
120
+ - `SDK_VERSION`: Default SDK version (overridden by --sdk-version)
121
+
122
+ ## Exit Codes
123
+
124
+ - `0`: Success
125
+ - `1`: Build failure (missing specs, compilation errors, etc.
package/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright [2025] [C7.digital]
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # @c7-digital/ledger
2
+
3
+ OpenAPI v2 compatible Daml ledger client (that could replace `@daml/ledger`) for the new Canton JSON API v2.
4
+
5
+ ## Overview
6
+
7
+ This package provides a TypeScript client for interacting with Canton's JSON Ledger API v2, which replaces the deprecated v1 API that `@daml/ledger` targets.
8
+
9
+ ## Features
10
+
11
+ - **Type-safe API**: Generated TypeScript types from OpenAPI specification
12
+ - **OpenAPI v2 Support**: Targets the new Canton JSON API v2 endpoints
13
+ - **Auto-generated Types**: Uses `openapi-typescript` to generate accurate type definitions
14
+
15
+ ## Versioning
16
+
17
+ This package follows the Canton SDK versioning scheme. The package version matches the Canton OpenAPI specification version used to generate the types.
18
+
19
+ **Current version**: `3.4.7`
20
+
21
+ - Corresponds to Canton SDK version `3.4.7`
22
+ - Types are generated from the OpenAPI spec for this specific Canton version
23
+ - When Canton releases a new version, this package will be updated to match
24
+
25
+ **Version compatibility**: Use the package version that matches your Canton participant node version for best compatibility.
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pnpm install @c7-digital/ledger
31
+ ```
32
+
33
+ Or build from source:
34
+
35
+ ```bash
36
+ pnpm install
37
+ pnpm build
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```typescript
43
+ import { Ledger } from "@c7-digital/ledger";
44
+
45
+ const ledger = new Ledger({
46
+ token: "your-jwt-token",
47
+ httpBaseUrl: "http://localhost:7575",
48
+ });
49
+
50
+ // Query contracts
51
+ const contracts = await ledger.query(MyTemplate);
52
+
53
+ // Create contracts
54
+ const result = await ledger.create(MyTemplate, payload, [actAsParty]);
55
+
56
+ // Exercise choices
57
+ const choiceResult = await ledger.exercise(MyChoice, contractId, argument, [
58
+ actAsParty,
59
+ ]);
60
+ ```
61
+
62
+ ## Migration from @daml/ledger
63
+
64
+ Key differences:
65
+
66
+ - `create()` and `exercise()` methods now require an `actAs` parameter
67
+ - Some method signatures have been updated to match OpenAPI v2 spec
68
+ - New type definitions generated from OpenAPI specification
69
+
70
+ ## Development
71
+
72
+ ```bash
73
+ # Build the package
74
+ pnpm build
75
+
76
+ # Clean build artifacts
77
+ pnpm clean
78
+
79
+ # Watch for changes
80
+ pnpm watch
81
+
82
+ # Run tests
83
+ pnpm test
84
+
85
+ # Lint code
86
+ pnpm lint
87
+ ```
88
+
89
+ ## OpenAPI Specification
90
+
91
+ The package uses the OpenAPI specification from Canton 3.4.7. The spec is saved as a version specific file (e.x. `openapi_3.4.7.yaml`) and types are automatically generated into `src/generated/api.ts`.
92
+
93
+ To update the specification:
94
+
95
+ 1. Download from docs.digitalasset.com or from your participant node.
96
+ 2. Update the build script to use the new SDK version
97
+ 3. Run `pnpm build` to regenerate types
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env tsx
2
+ /**
3
+ * Unified build script that uses SDK version-based spec files and runs all build steps
4
+ */
5
+ /**
6
+ * Main build function - builds both regular and lite versions
7
+ */
8
+ declare function build(): Promise<void>;
9
+ export { build };
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env tsx
2
+ /**
3
+ * Unified build script that uses SDK version-based spec files and runs all build steps
4
+ */
5
+ import { join, dirname } from "path";
6
+ import { fileURLToPath } from "url";
7
+ import { exec } from "child_process";
8
+ import { promisify } from "util";
9
+ import { readdir, writeFile, mkdir, unlink, copyFile } from "fs/promises";
10
+ import { existsSync } from "fs";
11
+ import { brandTypes } from "./enhance-types.js";
12
+ import { generateSchemaModule } from "./generate-schema-modules.js";
13
+ import { generateAsyncApiTypes } from "./generate-asyncapi-types.js";
14
+ const execAsync = promisify(exec);
15
+ const __filename = fileURLToPath(import.meta.url);
16
+ const __dirname = dirname(__filename);
17
+ const projectRoot = join(__dirname, "..");
18
+ /**
19
+ * Get SDK version from command line arguments or discover latest
20
+ */
21
+ function getSdkVersion() {
22
+ const args = process.argv.slice(2);
23
+ const versionArg = args.find(arg => arg.startsWith("--sdk-version="));
24
+ if (versionArg) {
25
+ return versionArg.split("=")[1];
26
+ }
27
+ return undefined;
28
+ }
29
+ /**
30
+ * Discover spec files based on SDK version or find latest version-based specs
31
+ */
32
+ async function discoverSpecFiles(sdkVersion) {
33
+ const specsDir = join(projectRoot, "specs");
34
+ const files = await readdir(specsDir);
35
+ if (sdkVersion) {
36
+ console.log(`🔍 Looking for spec files with SDK version: ${sdkVersion}`);
37
+ const openApiFile = `openapi_${sdkVersion}.yaml`;
38
+ const asyncApiFile = `asyncapi_${sdkVersion}.yaml`;
39
+ const result = {};
40
+ if (files.includes(openApiFile)) {
41
+ result.openapi = join(specsDir, openApiFile);
42
+ console.log(`📄 Found OpenAPI spec: ${openApiFile}`);
43
+ }
44
+ else {
45
+ console.warn(`⚠️ OpenAPI spec not found: ${openApiFile}`);
46
+ }
47
+ if (files.includes(asyncApiFile)) {
48
+ result.asyncapi = join(specsDir, asyncApiFile);
49
+ console.log(`📄 Found AsyncAPI spec: ${asyncApiFile}`);
50
+ }
51
+ else {
52
+ console.warn(`⚠️ AsyncAPI spec not found: ${asyncApiFile}`);
53
+ }
54
+ return { specs: result, version: sdkVersion };
55
+ }
56
+ else {
57
+ console.log("🔍 Auto-discovering latest version-based spec files...");
58
+ // Look for files with version pattern (not date pattern)
59
+ const versionPattern = /\d+\.\d+\.\d+(-snapshot\.\d{8}\.\d+)?/;
60
+ const openApiFiles = files
61
+ .filter(f => f.startsWith("openapi_") && f.endsWith(".yaml") && versionPattern.test(f))
62
+ .sort()
63
+ .reverse();
64
+ const asyncApiFiles = files
65
+ .filter(f => f.startsWith("asyncapi_") && f.endsWith(".yaml") && versionPattern.test(f))
66
+ .sort()
67
+ .reverse();
68
+ const result = {};
69
+ let detectedVersion = "";
70
+ if (openApiFiles.length > 0) {
71
+ result.openapi = join(specsDir, openApiFiles[0]);
72
+ console.log(`📄 Found OpenAPI spec: ${openApiFiles[0]}`);
73
+ // Extract version from filename
74
+ const match = openApiFiles[0].match(/openapi_(.+)\.yaml/);
75
+ if (match)
76
+ detectedVersion = match[1];
77
+ }
78
+ if (asyncApiFiles.length > 0) {
79
+ result.asyncapi = join(specsDir, asyncApiFiles[0]);
80
+ console.log(`📄 Found AsyncAPI spec: ${asyncApiFiles[0]}`);
81
+ // Use version from AsyncAPI if OpenAPI wasn't found
82
+ if (!detectedVersion) {
83
+ const match = asyncApiFiles[0].match(/asyncapi_(.+)\.yaml/);
84
+ if (match)
85
+ detectedVersion = match[1];
86
+ }
87
+ }
88
+ if (!detectedVersion) {
89
+ throw new Error("Could not detect SDK version from spec files. Please specify --sdk-version=<version>");
90
+ }
91
+ console.log(`🎯 Detected SDK version: ${detectedVersion}`);
92
+ return { specs: result, version: detectedVersion };
93
+ }
94
+ }
95
+ /**
96
+ * Generate OpenAPI types using openapi-typescript
97
+ */
98
+ async function generateTypes(specPath) {
99
+ console.log("🔄 Generating OpenAPI types...");
100
+ const outputPath = join(projectRoot, "src", "generated", "api.ts");
101
+ try {
102
+ const { stdout, stderr } = await execAsync(`pnpm exec openapi-typescript "${specPath}" --output "${outputPath}"`);
103
+ if (stderr && !stderr.includes("Warning")) {
104
+ console.warn("openapi-typescript warnings:", stderr);
105
+ }
106
+ if (stdout) {
107
+ console.log(stdout);
108
+ }
109
+ console.log("✅ Generated OpenAPI types");
110
+ }
111
+ catch (error) {
112
+ console.error("❌ Error generating OpenAPI types:", error.message);
113
+ throw error;
114
+ }
115
+ }
116
+ /**
117
+ * Generate schema modules for both OpenAPI and AsyncAPI
118
+ */
119
+ function generateSchemaModules(specs) {
120
+ console.log("🔄 Generating schema modules...");
121
+ const outputDir = join(projectRoot, "src", "generated");
122
+ if (specs.openapi) {
123
+ generateSchemaModule(specs.openapi, join(outputDir, "openapi-schema.ts"), "OPENAPI_SCHEMA");
124
+ }
125
+ if (specs.asyncapi) {
126
+ generateSchemaModule(specs.asyncapi, join(outputDir, "asyncapi-schema.ts"), "ASYNCAPI_SCHEMA");
127
+ }
128
+ console.log("✅ All schema modules generated");
129
+ }
130
+ /**
131
+ * Ensure the generated directory exists
132
+ */
133
+ async function ensureGeneratedDirectory() {
134
+ const outputDir = join(projectRoot, "src", "generated");
135
+ await mkdir(outputDir, { recursive: true });
136
+ }
137
+ /**
138
+ * Clean up any temporary files
139
+ */
140
+ async function cleanupTempFiles() {
141
+ const generatedDir = join(projectRoot, "src", "generated");
142
+ const tempFiles = [
143
+ join(generatedDir, "api.ts.tmp"),
144
+ join(generatedDir, "async-api.ts.tmp"),
145
+ join(projectRoot, "temp-asyncapi-as-openapi.yaml"),
146
+ ];
147
+ for (const tempFile of tempFiles) {
148
+ if (existsSync(tempFile)) {
149
+ try {
150
+ await unlink(tempFile);
151
+ console.log(`🧹 Cleaned up ${tempFile}`);
152
+ }
153
+ catch (error) {
154
+ // Ignore cleanup errors, but log them
155
+ console.warn(`⚠️ Could not clean up ${tempFile}:`, error.message);
156
+ }
157
+ }
158
+ }
159
+ }
160
+ /**
161
+ * Generate SDK version constant file
162
+ */
163
+ async function generateSdkVersionFile(version) {
164
+ console.log("🔄 Generating SDK version constant...");
165
+ const outputDir = join(projectRoot, "src", "generated");
166
+ const outputPath = join(outputDir, "sdk-version.ts");
167
+ const content = `// Auto-generated file - do not edit manually
168
+ // Generated from SDK version: ${version}
169
+
170
+ export const SDK_VERSION = "${version}";
171
+ `;
172
+ await writeFile(outputPath, content, "utf-8");
173
+ console.log(`✅ Generated SDK version constant: ${version}`);
174
+ }
175
+ /**
176
+ * Brand API types with value.proto constraints (in-place)
177
+ */
178
+ function brandApiTypes() {
179
+ console.log("🔄 Branding API types in-place...");
180
+ // Brand OpenAPI types (overwrite original file)
181
+ const apiPath = join(projectRoot, "src", "generated", "api.ts");
182
+ brandTypes(apiPath, apiPath, "OpenAPI");
183
+ // Brand AsyncAPI types (overwrite original file)
184
+ const asyncApiPath = join(projectRoot, "src", "generated", "async-api.ts");
185
+ brandTypes(asyncApiPath, asyncApiPath, "AsyncAPI");
186
+ console.log("✅ All types branded in-place");
187
+ }
188
+ /**
189
+ * Create stub schema files for lite build
190
+ */
191
+ async function createStubSchemaFiles() {
192
+ console.log("🔄 Creating stub schema files for lite build...");
193
+ const outputDir = join(projectRoot, "src", "generated");
194
+ const openApiStub = `// Stub file for lite build - no schema content
195
+ export const OPENAPI_SCHEMA = "";
196
+ `;
197
+ const asyncApiStub = `// Stub file for lite build - no schema content
198
+ export const ASYNCAPI_SCHEMA = "";
199
+ `;
200
+ await writeFile(join(outputDir, "openapi-schema.ts"), openApiStub, "utf-8");
201
+ await writeFile(join(outputDir, "asyncapi-schema.ts"), asyncApiStub, "utf-8");
202
+ console.log("✅ Created stub schema files");
203
+ }
204
+ /**
205
+ * Replace validation module with lite version in lib-lite
206
+ */
207
+ async function useLiteValidation() {
208
+ console.log("🔄 Replacing validation with lite version...");
209
+ const libLiteDir = join(projectRoot, "lib-lite", "src");
210
+ // Copy validation-lite.js over validation.js
211
+ const liteValidationJs = join(libLiteDir, "validation-lite.js");
212
+ const validationJs = join(libLiteDir, "validation.js");
213
+ if (existsSync(liteValidationJs)) {
214
+ await copyFile(liteValidationJs, validationJs);
215
+ await unlink(liteValidationJs);
216
+ console.log("✅ Replaced validation.js with lite version");
217
+ }
218
+ // Copy validation-lite.d.ts over validation.d.ts
219
+ const liteValidationDts = join(libLiteDir, "validation-lite.d.ts");
220
+ const validationDts = join(libLiteDir, "validation.d.ts");
221
+ if (existsSync(liteValidationDts)) {
222
+ await copyFile(liteValidationDts, validationDts);
223
+ await unlink(liteValidationDts);
224
+ console.log("✅ Replaced validation.d.ts with lite version");
225
+ }
226
+ // Also remove validation-lite files from lib/ (they shouldn't be there)
227
+ const libDir = join(projectRoot, "lib", "src");
228
+ const libLiteValidationJs = join(libDir, "validation-lite.js");
229
+ const libLiteValidationDts = join(libDir, "validation-lite.d.ts");
230
+ if (existsSync(libLiteValidationJs)) {
231
+ await unlink(libLiteValidationJs);
232
+ }
233
+ if (existsSync(libLiteValidationDts)) {
234
+ await unlink(libLiteValidationDts);
235
+ }
236
+ }
237
+ /**
238
+ * Compile TypeScript code
239
+ */
240
+ async function compileTypeScript(outDir = "lib") {
241
+ console.log(`🔄 Compiling TypeScript to ${outDir}...`);
242
+ try {
243
+ let tscCommand = `pnpm exec tsc -p ${join(projectRoot, "tsconfig.json")}`;
244
+ let aliasCommand = `pnpm exec tsc-alias -p ${join(projectRoot, "tsconfig.json")}`;
245
+ if (outDir !== "lib") {
246
+ // Create a temporary tsconfig for different output directory
247
+ const tempTsConfig = {
248
+ extends: "./tsconfig.json",
249
+ compilerOptions: {
250
+ outDir: `./${outDir}`,
251
+ declarationDir: `./${outDir}`,
252
+ },
253
+ };
254
+ const tempConfigPath = join(projectRoot, "tsconfig.temp.json");
255
+ await writeFile(tempConfigPath, JSON.stringify(tempTsConfig, null, 2), "utf-8");
256
+ tscCommand = `pnpm exec tsc -p ${tempConfigPath}`;
257
+ aliasCommand = `pnpm exec tsc-alias -p ${tempConfigPath}`;
258
+ }
259
+ // Run tsc first (tsc-alias depends on tsc output)
260
+ const { stdout: tscStdout, stderr: tscStderr } = await execAsync(tscCommand);
261
+ if (tscStderr) {
262
+ console.error("TypeScript compiler errors/warnings:");
263
+ console.error(tscStderr);
264
+ }
265
+ if (tscStdout) {
266
+ console.log("TypeScript compiler output:");
267
+ console.log(tscStdout);
268
+ }
269
+ // Run tsc-alias after tsc completes
270
+ const { stdout: aliasStdout, stderr: aliasStderr } = await execAsync(aliasCommand);
271
+ if (aliasStderr) {
272
+ console.warn("tsc-alias warnings:", aliasStderr);
273
+ }
274
+ if (aliasStdout) {
275
+ console.log(aliasStdout);
276
+ }
277
+ // Clean up temp config if created
278
+ if (outDir !== "lib") {
279
+ const tempConfigPath = join(projectRoot, "tsconfig.temp.json");
280
+ if (existsSync(tempConfigPath)) {
281
+ await unlink(tempConfigPath);
282
+ }
283
+ }
284
+ console.log(`✅ TypeScript compilation complete for ${outDir}`);
285
+ }
286
+ catch (error) {
287
+ console.error(`❌ Error compiling TypeScript to ${outDir}:`);
288
+ console.error(error.message);
289
+ // If the error has stdout/stderr, display them
290
+ if (error && typeof error === "object" && "stdout" in error && error.stdout) {
291
+ console.error("TypeScript stdout:");
292
+ console.error(error.stdout);
293
+ }
294
+ if (error && typeof error === "object" && "stderr" in error && error.stderr) {
295
+ console.error("TypeScript stderr:");
296
+ console.error(error.stderr);
297
+ }
298
+ console.error("💡 Note: TypeScript compilation failed, but code generation was successful.");
299
+ console.error("💡 Check the errors above and fix any type issues in your source files.");
300
+ throw error;
301
+ }
302
+ }
303
+ /**
304
+ * Main build function - builds both regular and lite versions
305
+ */
306
+ async function build() {
307
+ console.log("🚀 Starting SDK version-aware build process...");
308
+ try {
309
+ // Step 1: Get SDK version and discover spec files
310
+ const sdkVersion = getSdkVersion();
311
+ const { specs, version } = await discoverSpecFiles(sdkVersion);
312
+ if (!specs.openapi && !specs.asyncapi) {
313
+ throw new Error(`No spec files found for SDK version: ${version}`);
314
+ }
315
+ // Step 2: Ensure generated directory exists
316
+ await ensureGeneratedDirectory();
317
+ // Step 3: Generate SDK version constant (independent, can run early)
318
+ const sdkVersionPromise = generateSdkVersionFile(version);
319
+ // Step 4: Run type generation in parallel (all independent)
320
+ const parallelTasks = [];
321
+ if (specs.openapi) {
322
+ parallelTasks.push(generateTypes(specs.openapi));
323
+ }
324
+ if (specs.asyncapi) {
325
+ parallelTasks.push(generateAsyncApiTypes(specs.asyncapi));
326
+ }
327
+ // Wait for SDK version file and all parallel type generation
328
+ await Promise.all([sdkVersionPromise, ...parallelTasks]);
329
+ // Step 5: Brand types (depends on generated types)
330
+ brandApiTypes();
331
+ console.log("🎯 Building regular version with full schemas...");
332
+ // Step 6a: Generate full schema modules for regular build
333
+ generateSchemaModules(specs);
334
+ // Step 6b: Compile regular TypeScript (depends on all previous steps)
335
+ await compileTypeScript("lib");
336
+ console.log("🎯 Building lite version without schemas...");
337
+ // Step 7a: Create stub schema files for lite build
338
+ await createStubSchemaFiles();
339
+ // Step 7b: Compile lite TypeScript to separate directory
340
+ await compileTypeScript("lib-lite");
341
+ // Step 7c: Replace validation with lite version (no yaml dependency)
342
+ await useLiteValidation();
343
+ // Step 8: Clean up any temporary files
344
+ await cleanupTempFiles();
345
+ console.log(`🎉 Both regular and lite builds completed successfully for version: ${version}!`);
346
+ console.log(`📦 Regular build: lib/ (with validation schemas)`);
347
+ console.log(`📦 Lite build: lib-lite/ (without validation schemas)`);
348
+ }
349
+ catch (error) {
350
+ console.error("❌ Build failed:", error.message);
351
+ // Attempt cleanup even on failure
352
+ try {
353
+ await cleanupTempFiles();
354
+ }
355
+ catch (cleanupError) {
356
+ console.warn("⚠️ Could not clean up temp files after build failure");
357
+ }
358
+ process.exit(1);
359
+ }
360
+ }
361
+ // Run the build if this script is executed directly
362
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
363
+ build();
364
+ }
365
+ // Export for use in other scripts
366
+ export { build };
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ declare function brandTypes(inputPath: string, outputPath: string, label?: string): void;
3
+ export { brandTypes };