@reactive-contracts/compiler 0.1.0-beta

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 Mariano Álvarez
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.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Import the compiled CLI
4
+ import('../index.cli.js').catch((error) => {
5
+ console.error('Failed to start CLI:', error);
6
+ process.exit(1);
7
+ });
package/dist/index.cjs ADDED
@@ -0,0 +1,474 @@
1
+ 'use strict';
2
+
3
+ var promises = require('fs/promises');
4
+ var path = require('path');
5
+
6
+ // src/config/index.ts
7
+ function defineConfig(config) {
8
+ return config;
9
+ }
10
+
11
+ // src/validator/index.ts
12
+ function validateContract(contract) {
13
+ const errors = [];
14
+ const warnings = [];
15
+ if (!contract || typeof contract !== "object") {
16
+ errors.push("Contract must be a valid object");
17
+ return { valid: false, errors, warnings };
18
+ }
19
+ if (contract._brand !== "Contract") {
20
+ errors.push("Invalid contract: missing _brand property");
21
+ return { valid: false, errors, warnings };
22
+ }
23
+ const { definition } = contract;
24
+ if (!definition.name || typeof definition.name !== "string") {
25
+ errors.push("Contract must have a valid name (non-empty string)");
26
+ } else if (!/^[A-Z][a-zA-Z0-9]*$/.test(definition.name)) {
27
+ warnings.push(
28
+ "Contract name should be in PascalCase (e.g., UserProfile, not userProfile or user_profile)"
29
+ );
30
+ }
31
+ if (!definition.intent || typeof definition.intent !== "string") {
32
+ errors.push("Contract must have a valid intent (non-empty string)");
33
+ } else if (definition.intent.length < 10) {
34
+ warnings.push("Intent should be descriptive (at least 10 characters)");
35
+ }
36
+ if (!definition.shape || typeof definition.shape !== "object") {
37
+ errors.push("Contract must have a valid shape definition");
38
+ } else {
39
+ validateShape(definition.shape, "", errors, warnings);
40
+ }
41
+ if (definition.constraints) {
42
+ validateConstraints(definition.constraints, errors);
43
+ }
44
+ if (definition.reactivity) {
45
+ validateReactivity(definition.reactivity, definition.shape, errors, warnings);
46
+ }
47
+ if (definition.versioning) {
48
+ validateVersioning(definition.versioning, errors, warnings);
49
+ }
50
+ return {
51
+ valid: errors.length === 0,
52
+ errors,
53
+ warnings
54
+ };
55
+ }
56
+ function validateShape(shape, path, errors, warnings) {
57
+ if (!shape || typeof shape !== "object") {
58
+ errors.push(`Invalid shape at ${path || "root"}: must be an object`);
59
+ return;
60
+ }
61
+ const keys = Object.keys(shape);
62
+ if (keys.length === 0) {
63
+ warnings.push(`Shape at ${path || "root"} is empty`);
64
+ }
65
+ for (const key of keys) {
66
+ const fieldPath = path ? `${path}.${key}` : key;
67
+ const value = shape[key];
68
+ if (!value) {
69
+ errors.push(`Field "${fieldPath}" has undefined value`);
70
+ continue;
71
+ }
72
+ if (!/^[a-z][a-zA-Z0-9]*$/.test(key)) {
73
+ warnings.push(
74
+ `Field name "${fieldPath}" should be in camelCase (e.g., firstName, not first_name)`
75
+ );
76
+ }
77
+ validateTypeDefinition(value, fieldPath, errors, warnings);
78
+ }
79
+ }
80
+ function validateTypeDefinition(type, path, errors, warnings) {
81
+ if (typeof type === "string") {
82
+ const validPrimitives = ["string", "number", "boolean", "Date", "null", "undefined"];
83
+ const isURL = type === "URL" || type.startsWith("URL<");
84
+ if (!validPrimitives.includes(type) && !isURL) {
85
+ errors.push(`Invalid type at ${path}: "${type}" is not a valid primitive or URL type`);
86
+ }
87
+ if (isURL && type !== "URL") {
88
+ const urlMatch = type.match(/^URL<(.+)>$/);
89
+ if (!urlMatch) {
90
+ errors.push(`Invalid URL type at ${path}: must be "URL" or "URL<options>"`);
91
+ }
92
+ }
93
+ } else if (typeof type === "object" && type !== null) {
94
+ if ("_brand" in type && type._brand === "DerivedField") {
95
+ validateDerivedField(
96
+ type,
97
+ path,
98
+ errors);
99
+ } else {
100
+ validateShape(type, path, errors, warnings);
101
+ }
102
+ } else {
103
+ errors.push(`Invalid type at ${path}: must be a string, object, or DerivedField`);
104
+ }
105
+ }
106
+ function validateDerivedField(field, path, errors, _warnings) {
107
+ if (typeof field.derive !== "function") {
108
+ errors.push(`Derived field at ${path} must have a derive function`);
109
+ }
110
+ if (field.dependencies && !Array.isArray(field.dependencies)) {
111
+ errors.push(`Derived field dependencies at ${path} must be an array`);
112
+ }
113
+ if (field.preferredLayer && !["client", "edge", "origin"].includes(field.preferredLayer)) {
114
+ errors.push(`Derived field preferredLayer at ${path} must be 'client', 'edge', or 'origin'`);
115
+ }
116
+ if (field.dependencies && Array.isArray(field.dependencies)) {
117
+ for (const dep of field.dependencies) {
118
+ if (typeof dep !== "string") {
119
+ errors.push(`Derived field dependency at ${path} must be a string`);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ function validateConstraints(constraints, errors, _warnings) {
125
+ if (constraints.latency) {
126
+ const { max, fallback } = constraints.latency;
127
+ if (!max || typeof max !== "string") {
128
+ errors.push('Latency constraint must have a max value (e.g., "100ms")');
129
+ } else {
130
+ if (!/^\d+(ms|s|m)$/.test(max)) {
131
+ errors.push(`Invalid latency max format: "${max}". Use format like "100ms", "1s", or "1m"`);
132
+ }
133
+ }
134
+ if (fallback && !["cachedVersion", "degraded", "error"].includes(fallback)) {
135
+ errors.push('Latency fallback must be "cachedVersion", "degraded", or "error"');
136
+ }
137
+ }
138
+ if (constraints.freshness) {
139
+ const { maxAge, staleWhileRevalidate } = constraints.freshness;
140
+ if (!maxAge || typeof maxAge !== "string") {
141
+ errors.push("Freshness constraint must have a maxAge value");
142
+ } else if (!/^\d+(ms|s|m|h|d)$/.test(maxAge)) {
143
+ errors.push(
144
+ `Invalid freshness maxAge format: "${maxAge}". Use format like "5m", "1h", or "1d"`
145
+ );
146
+ }
147
+ if (staleWhileRevalidate && !/^\d+(ms|s|m|h|d)$/.test(staleWhileRevalidate)) {
148
+ errors.push(
149
+ `Invalid staleWhileRevalidate format: "${staleWhileRevalidate}". Use format like "5m", "1h", or "1d"`
150
+ );
151
+ }
152
+ }
153
+ if (constraints.availability) {
154
+ const { uptime, gracefulDegradation } = constraints.availability;
155
+ if (!uptime || typeof uptime !== "string") {
156
+ errors.push("Availability constraint must have an uptime value");
157
+ } else if (!/^\d+(\.\d+)?%$/.test(uptime)) {
158
+ errors.push(`Invalid uptime format: "${uptime}". Use format like "99.9%"`);
159
+ }
160
+ if (gracefulDegradation !== void 0 && typeof gracefulDegradation !== "boolean") {
161
+ errors.push("Availability gracefulDegradation must be a boolean");
162
+ }
163
+ }
164
+ }
165
+ function validateReactivity(reactivity, shape, errors, warnings) {
166
+ const allFields = /* @__PURE__ */ new Set();
167
+ collectFieldPaths(shape, "", allFields);
168
+ if (reactivity.realtime) {
169
+ if (!Array.isArray(reactivity.realtime)) {
170
+ errors.push("Reactivity realtime must be an array of field paths");
171
+ } else {
172
+ for (const field of reactivity.realtime) {
173
+ if (typeof field !== "string") {
174
+ errors.push("Realtime field must be a string");
175
+ } else if (!allFields.has(field)) {
176
+ warnings.push(`Realtime field "${field}" does not exist in shape`);
177
+ }
178
+ }
179
+ }
180
+ }
181
+ if (reactivity.static) {
182
+ if (!Array.isArray(reactivity.static)) {
183
+ errors.push("Reactivity static must be an array of field paths");
184
+ } else {
185
+ for (const field of reactivity.static) {
186
+ if (typeof field !== "string") {
187
+ errors.push("Static field must be a string");
188
+ } else if (!allFields.has(field)) {
189
+ warnings.push(`Static field "${field}" does not exist in shape`);
190
+ }
191
+ }
192
+ }
193
+ }
194
+ if (reactivity.polling) {
195
+ if (!Array.isArray(reactivity.polling)) {
196
+ errors.push("Reactivity polling must be an array");
197
+ } else {
198
+ for (const config of reactivity.polling) {
199
+ if (!config.field || typeof config.field !== "string") {
200
+ errors.push("Polling config must have a field property");
201
+ } else if (!allFields.has(config.field)) {
202
+ warnings.push(`Polling field "${config.field}" does not exist in shape`);
203
+ }
204
+ if (!config.interval || typeof config.interval !== "string") {
205
+ errors.push("Polling config must have an interval property");
206
+ } else if (!/^\d+(ms|s|m)$/.test(config.interval)) {
207
+ errors.push(
208
+ `Invalid polling interval format: "${config.interval}". Use format like "30s" or "5m"`
209
+ );
210
+ }
211
+ }
212
+ }
213
+ }
214
+ if (reactivity.eventDriven) {
215
+ if (!Array.isArray(reactivity.eventDriven)) {
216
+ errors.push("Reactivity eventDriven must be an array");
217
+ } else {
218
+ for (const config of reactivity.eventDriven) {
219
+ if (!config.field || typeof config.field !== "string") {
220
+ errors.push("EventDriven config must have a field property");
221
+ } else if (!allFields.has(config.field)) {
222
+ warnings.push(`EventDriven field "${config.field}" does not exist in shape`);
223
+ }
224
+ if (!config.on || !Array.isArray(config.on)) {
225
+ errors.push('EventDriven config must have an "on" array of event names');
226
+ } else if (config.on.length === 0) {
227
+ warnings.push(`EventDriven config for "${config.field}" has no events`);
228
+ }
229
+ }
230
+ }
231
+ }
232
+ }
233
+ function validateVersioning(versioning, errors, warnings) {
234
+ if (!versioning.version || typeof versioning.version !== "string") {
235
+ errors.push("Versioning must have a version string");
236
+ } else if (!/^\d+\.\d+\.\d+$/.test(versioning.version)) {
237
+ warnings.push(`Version "${versioning.version}" should follow semver format (e.g., "1.0.0")`);
238
+ }
239
+ if (versioning.deprecated && !Array.isArray(versioning.deprecated)) {
240
+ errors.push("Versioning deprecated must be an array of field paths");
241
+ }
242
+ if (versioning.migration && typeof versioning.migration !== "function") {
243
+ errors.push("Versioning migration must be a function");
244
+ }
245
+ }
246
+ function collectFieldPaths(shape, prefix, result) {
247
+ for (const [key, value] of Object.entries(shape)) {
248
+ const path = prefix ? `${prefix}.${key}` : key;
249
+ result.add(path);
250
+ if (typeof value === "object" && value !== null && !("_brand" in value) && typeof value !== "string") {
251
+ collectFieldPaths(value, path, result);
252
+ }
253
+ }
254
+ }
255
+
256
+ // src/analyzer/index.ts
257
+ function analyzeLatency(contract) {
258
+ const { definition } = contract;
259
+ const suggestions = [];
260
+ if (!definition.constraints?.latency) {
261
+ suggestions.push("Consider adding a latency constraint to ensure performance SLAs");
262
+ return {
263
+ status: "ok",
264
+ suggestions
265
+ };
266
+ }
267
+ const { max: maxLatency, fallback } = definition.constraints.latency;
268
+ const latencyMs = parseLatencyToMs(maxLatency);
269
+ if (latencyMs === null) {
270
+ return {
271
+ status: "error",
272
+ message: `Invalid latency format: ${maxLatency}`,
273
+ suggestions: ['Use format like "100ms", "1s", or "1m"']
274
+ };
275
+ }
276
+ const analysis = analyzeLatencyRequirement(latencyMs);
277
+ if (!fallback) {
278
+ suggestions.push("Consider specifying a fallback strategy (cachedVersion, degraded, or error)");
279
+ }
280
+ if (latencyMs < 50) {
281
+ suggestions.push(
282
+ "Very aggressive latency target (<50ms). Consider edge caching or CDN for static data."
283
+ );
284
+ } else if (latencyMs < 100) {
285
+ suggestions.push(
286
+ "Moderate latency target (<100ms). Ensure database queries are optimized and indexed."
287
+ );
288
+ } else if (latencyMs > 1e3) {
289
+ suggestions.push(
290
+ "High latency tolerance (>1s). Consider if this provides good user experience."
291
+ );
292
+ }
293
+ if (hasComplexDerivations(definition.shape)) {
294
+ suggestions.push(
295
+ "Contract contains derived fields. Consider computing these at edge or origin for better performance."
296
+ );
297
+ }
298
+ if (definition.reactivity?.realtime && definition.reactivity.realtime.length > 0) {
299
+ suggestions.push(
300
+ "Realtime fields require WebSocket connections. Ensure your infrastructure supports this."
301
+ );
302
+ }
303
+ return {
304
+ status: analysis.status,
305
+ estimated: analysis.estimated,
306
+ message: analysis.message,
307
+ suggestions
308
+ };
309
+ }
310
+ function parseLatencyToMs(latency) {
311
+ const match = latency.match(/^(\d+)(ms|s|m)$/);
312
+ if (!match || !match[1] || !match[2]) return null;
313
+ const value = parseInt(match[1], 10);
314
+ const unit = match[2];
315
+ switch (unit) {
316
+ case "ms":
317
+ return value;
318
+ case "s":
319
+ return value * 1e3;
320
+ case "m":
321
+ return value * 60 * 1e3;
322
+ default:
323
+ return null;
324
+ }
325
+ }
326
+ function analyzeLatencyRequirement(latencyMs) {
327
+ if (latencyMs < 10) {
328
+ return {
329
+ status: "error",
330
+ estimated: "Typically 50-100ms for database queries",
331
+ message: "Latency target <10ms is extremely difficult to achieve consistently"
332
+ };
333
+ }
334
+ if (latencyMs < 50) {
335
+ return {
336
+ status: "warning",
337
+ estimated: "Requires edge caching or CDN",
338
+ message: "Latency target <50ms requires careful optimization"
339
+ };
340
+ }
341
+ if (latencyMs <= 200) {
342
+ return {
343
+ status: "ok",
344
+ estimated: "Achievable with optimized queries and caching",
345
+ message: "Latency target is reasonable for most applications"
346
+ };
347
+ }
348
+ if (latencyMs <= 1e3) {
349
+ return {
350
+ status: "ok",
351
+ estimated: "Easily achievable with standard backend",
352
+ message: "Latency target is conservative and should be easy to meet"
353
+ };
354
+ }
355
+ return {
356
+ status: "warning",
357
+ estimated: "Very high tolerance",
358
+ message: "Consider if this latency provides acceptable user experience"
359
+ };
360
+ }
361
+ function hasComplexDerivations(shape) {
362
+ if (!shape || typeof shape !== "object") {
363
+ return false;
364
+ }
365
+ for (const value of Object.values(shape)) {
366
+ if (typeof value === "object" && value !== null) {
367
+ if ("_brand" in value && value._brand === "DerivedField") {
368
+ return true;
369
+ }
370
+ if (hasComplexDerivations(value)) {
371
+ return true;
372
+ }
373
+ }
374
+ }
375
+ return false;
376
+ }
377
+ async function generateFrontendTypes(contract, outputPath) {
378
+ const { definition } = contract;
379
+ const typeName = definition.name;
380
+ const typeDefinitions = generateTypeDefinitions(definition.shape, `${typeName}Shape`);
381
+ const content = `/**
382
+ * Auto-generated types for ${typeName} contract
383
+ * DO NOT EDIT - This file is generated by @reactive-contracts/compiler
384
+ */
385
+
386
+ import type { ContractStatus } from '@reactive-contracts/core';
387
+
388
+ ${typeDefinitions}
389
+
390
+ /**
391
+ * Parameters for ${typeName} contract
392
+ */
393
+ export interface ${typeName}Params {
394
+ // Add your params here based on contract requirements
395
+ [key: string]: unknown;
396
+ }
397
+
398
+ /**
399
+ * Full result type for ${typeName} contract
400
+ */
401
+ export interface ${typeName}Result {
402
+ data: ${typeName}Shape;
403
+ status: ContractStatus;
404
+ metadata: {
405
+ executionTime: number;
406
+ cacheHit: boolean;
407
+ derivedAt: 'client' | 'edge' | 'origin';
408
+ };
409
+ }
410
+
411
+ /**
412
+ * Contract intent: ${definition.intent}
413
+ */
414
+ export const ${typeName}Intent = '${definition.intent}' as const;
415
+ `;
416
+ await promises.mkdir(path.dirname(outputPath), { recursive: true });
417
+ await promises.writeFile(outputPath, content, "utf-8");
418
+ }
419
+ function generateTypeDefinitions(shape, typeName) {
420
+ const fields = generateShapeFields(shape, 0);
421
+ return `export interface ${typeName} {
422
+ ${fields}
423
+ }`;
424
+ }
425
+ function generateShapeFields(shape, indent) {
426
+ const indentStr = " ".repeat(indent + 1);
427
+ const lines = [];
428
+ for (const [key, value] of Object.entries(shape)) {
429
+ const typeStr = generateTypeString(value, indent + 1);
430
+ lines.push(`${indentStr}${key}: ${typeStr};`);
431
+ }
432
+ return lines.join("\n");
433
+ }
434
+ function generateTypeString(type, indent) {
435
+ if (typeof type === "string") {
436
+ switch (type) {
437
+ case "string":
438
+ return "string";
439
+ case "number":
440
+ return "number";
441
+ case "boolean":
442
+ return "boolean";
443
+ case "Date":
444
+ return "Date";
445
+ case "null":
446
+ return "null";
447
+ case "undefined":
448
+ return "undefined";
449
+ default:
450
+ if (type === "URL" || type.startsWith("URL<")) {
451
+ return "string";
452
+ }
453
+ return "any";
454
+ }
455
+ } else if (typeof type === "object" && type !== null) {
456
+ if ("_brand" in type && type._brand === "DerivedField") {
457
+ return "any";
458
+ } else {
459
+ const fields = generateShapeFields(type, indent);
460
+ const indentStr = " ".repeat(indent);
461
+ return `{
462
+ ${fields}
463
+ ${indentStr}}`;
464
+ }
465
+ }
466
+ return "any";
467
+ }
468
+
469
+ exports.analyzeLatency = analyzeLatency;
470
+ exports.defineConfig = defineConfig;
471
+ exports.generateFrontendTypes = generateFrontendTypes;
472
+ exports.validateContract = validateContract;
473
+ //# sourceMappingURL=index.cjs.map
474
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/index.ts","../src/validator/index.ts","../src/analyzer/index.ts","../src/generator/index.ts"],"names":["mkdir","dirname","writeFile"],"mappings":";;;;;;AAKO,SAAS,aAAa,MAAA,EAA0C;AACrE,EAAA,OAAO,MAAA;AACT;;;ACOO,SAAS,iBAAiB,QAAA,EAAsC;AACrE,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,MAAM,WAAqB,EAAC;AAG5B,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,MAAA,CAAO,KAAK,iCAAiC,CAAA;AAC7C,IAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,MAAA,EAAQ,QAAA,EAAS;AAAA,EAC1C;AAEA,EAAA,IAAI,QAAA,CAAS,WAAW,UAAA,EAAY;AAClC,IAAA,MAAA,CAAO,KAAK,2CAA2C,CAAA;AACvD,IAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,MAAA,EAAQ,QAAA,EAAS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A,MACT,KAAK,MAAA;AACH,QAAA,OAAO,MAAA;AAAA,MACT,KAAK,MAAA;AACH,QAAA,OAAO,MAAA;AAAA,MACT,KAAK,WAAA;AACH,QAAA,OAAO,WAAA;AAAA,MACT;AACE,QAAA,IAAI,IAAA,KAAS,KAAA,IAAS,IAAA,CAAK,UAAA,CAAW,MAAM,CAAA,EAAG;AAC7C,UAAA,OAAO,QAAA;AAAA,QACT;AACA,QAAA,OAAO,KAAA;AAAA;AACX,EACF,CAAA,MAAA,IAAW,OAAO,IAAA,KAAS,QAAA,IAAY,SAAS,IAAA,EAAM;AAEpD,IAAA,IAAI,QAAA,IAAY,IAAA,IAAQ,IAAA,CAAK,MAAA,KAAW,cAAA,EAAgB;AAGtD,MAAA,OAAO,KAAA;AAAA,IACT,CAAA,MAAO;AAEL,MAAA,MAAM,MAAA,GAAS,mBAAA,CAAoB,IAAA,EAAyB,MAAM,CAAA;AAClE,MAAA,MAAM,SAAA,GAAY,IAAA,CAAK,MAAA,CAAO,MAAM,CAAA;AACpC,MAAA,OAAO,CAAA;AAAA,EAAM,MAAM;AAAA,EAAK,SAAS,CAAA,CAAA,CAAA;AAAA,IACnC;AAAA,EACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["import type { CompilerConfig, ConfigDefinition } from '../types.js';\n\n/**\n * Define a Reactive Contracts compiler configuration\n */\nexport function defineConfig(config: CompilerConfig): ConfigDefinition {\n return config;\n}\n\n/**\n * Load configuration from file\n */\nexport async function loadConfig(\n _configPath: string = './rcontracts.config.ts'\n): Promise<CompilerConfig> {\n // TODO: Implement config loading\n return {\n contracts: './contracts/**/*.contract.ts',\n output: {\n frontend: './generated/frontend',\n backend: './generated/backend',\n runtime: './generated/runtime',\n },\n };\n}\n","import type {\n Contract,\n ShapeDefinition,\n TypeDefinition,\n DerivedField,\n ContractConstraints,\n ReactivityConfig,\n VersioningConfig,\n} from '@reactive-contracts/core';\nimport type { ValidationResult } from '../types.js';\n\n/**\n * Validate a contract structure\n */\nexport function validateContract(contract: Contract): ValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Validate basic contract structure\n if (!contract || typeof contract !== 'object') {\n errors.push('Contract must be a valid object');\n return { valid: false, errors, warnings };\n }\n\n if (contract._brand !== 'Contract') {\n errors.push('Invalid contract: missing _brand property');\n return { valid: false, errors, warnings };\n }\n\n const { definition } = contract;\n\n // Validate name\n if (!definition.name || typeof definition.name !== 'string') {\n errors.push('Contract must have a valid name (non-empty string)');\n } else if (!/^[A-Z][a-zA-Z0-9]*$/.test(definition.name)) {\n warnings.push(\n 'Contract name should be in PascalCase (e.g., UserProfile, not userProfile or user_profile)'\n );\n }\n\n // Validate intent\n if (!definition.intent || typeof definition.intent !== 'string') {\n errors.push('Contract must have a valid intent (non-empty string)');\n } else if (definition.intent.length < 10) {\n warnings.push('Intent should be descriptive (at least 10 characters)');\n }\n\n // Validate shape\n if (!definition.shape || typeof definition.shape !== 'object') {\n errors.push('Contract must have a valid shape definition');\n } else {\n validateShape(definition.shape, '', errors, warnings);\n }\n\n // Validate constraints\n if (definition.constraints) {\n validateConstraints(definition.constraints, errors, warnings);\n }\n\n // Validate reactivity\n if (definition.reactivity) {\n validateReactivity(definition.reactivity, definition.shape, errors, warnings);\n }\n\n // Validate versioning\n if (definition.versioning) {\n validateVersioning(definition.versioning, errors, warnings);\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Validate shape definition recursively\n */\nfunction validateShape(\n shape: ShapeDefinition,\n path: string,\n errors: string[],\n warnings: string[]\n): void {\n if (!shape || typeof shape !== 'object') {\n errors.push(`Invalid shape at ${path || 'root'}: must be an object`);\n return;\n }\n\n const keys = Object.keys(shape);\n if (keys.length === 0) {\n warnings.push(`Shape at ${path || 'root'} is empty`);\n }\n\n for (const key of keys) {\n const fieldPath = path ? `${path}.${key}` : key;\n const value = shape[key];\n\n if (!value) {\n errors.push(`Field \"${fieldPath}\" has undefined value`);\n continue;\n }\n\n // Validate field name\n if (!/^[a-z][a-zA-Z0-9]*$/.test(key)) {\n warnings.push(\n `Field name \"${fieldPath}\" should be in camelCase (e.g., firstName, not first_name)`\n );\n }\n\n // Validate field type\n validateTypeDefinition(value, fieldPath, errors, warnings);\n }\n}\n\n/**\n * Validate a type definition\n */\nfunction validateTypeDefinition(\n type: TypeDefinition,\n path: string,\n errors: string[],\n warnings: string[]\n): void {\n if (typeof type === 'string') {\n // Primitive type or URL type\n const validPrimitives = ['string', 'number', 'boolean', 'Date', 'null', 'undefined'];\n const isURL = type === 'URL' || type.startsWith('URL<');\n\n if (!validPrimitives.includes(type) && !isURL) {\n errors.push(`Invalid type at ${path}: \"${type}\" is not a valid primitive or URL type`);\n }\n\n // Validate URL optimization syntax\n if (isURL && type !== 'URL') {\n const urlMatch = type.match(/^URL<(.+)>$/);\n if (!urlMatch) {\n errors.push(`Invalid URL type at ${path}: must be \"URL\" or \"URL<options>\"`);\n }\n }\n } else if (typeof type === 'object' && type !== null) {\n // Check if it's a DerivedField\n if ('_brand' in type && type._brand === 'DerivedField') {\n validateDerivedField(\n type as DerivedField<Record<string, unknown>, unknown>,\n path,\n errors,\n warnings\n );\n } else {\n // Nested shape\n validateShape(type as ShapeDefinition, path, errors, warnings);\n }\n } else {\n errors.push(`Invalid type at ${path}: must be a string, object, or DerivedField`);\n }\n}\n\n/**\n * Validate derived field\n */\nfunction validateDerivedField(\n field: DerivedField<Record<string, unknown>, unknown>,\n path: string,\n errors: string[],\n _warnings: string[]\n): void {\n if (typeof field.derive !== 'function') {\n errors.push(`Derived field at ${path} must have a derive function`);\n }\n\n if (field.dependencies && !Array.isArray(field.dependencies)) {\n errors.push(`Derived field dependencies at ${path} must be an array`);\n }\n\n if (field.preferredLayer && !['client', 'edge', 'origin'].includes(field.preferredLayer)) {\n errors.push(`Derived field preferredLayer at ${path} must be 'client', 'edge', or 'origin'`);\n }\n\n if (field.dependencies && Array.isArray(field.dependencies)) {\n for (const dep of field.dependencies) {\n if (typeof dep !== 'string') {\n errors.push(`Derived field dependency at ${path} must be a string`);\n }\n }\n }\n}\n\n/**\n * Validate contract constraints\n */\nfunction validateConstraints(\n constraints: ContractConstraints,\n errors: string[],\n _warnings: string[]\n): void {\n // Validate latency constraint\n if (constraints.latency) {\n const { max, fallback } = constraints.latency;\n\n if (!max || typeof max !== 'string') {\n errors.push('Latency constraint must have a max value (e.g., \"100ms\")');\n } else {\n // Validate time format\n if (!/^\\d+(ms|s|m)$/.test(max)) {\n errors.push(`Invalid latency max format: \"${max}\". Use format like \"100ms\", \"1s\", or \"1m\"`);\n }\n }\n\n if (fallback && !['cachedVersion', 'degraded', 'error'].includes(fallback)) {\n errors.push('Latency fallback must be \"cachedVersion\", \"degraded\", or \"error\"');\n }\n }\n\n // Validate freshness constraint\n if (constraints.freshness) {\n const { maxAge, staleWhileRevalidate } = constraints.freshness;\n\n if (!maxAge || typeof maxAge !== 'string') {\n errors.push('Freshness constraint must have a maxAge value');\n } else if (!/^\\d+(ms|s|m|h|d)$/.test(maxAge)) {\n errors.push(\n `Invalid freshness maxAge format: \"${maxAge}\". Use format like \"5m\", \"1h\", or \"1d\"`\n );\n }\n\n if (staleWhileRevalidate && !/^\\d+(ms|s|m|h|d)$/.test(staleWhileRevalidate)) {\n errors.push(\n `Invalid staleWhileRevalidate format: \"${staleWhileRevalidate}\". Use format like \"5m\", \"1h\", or \"1d\"`\n );\n }\n }\n\n // Validate availability constraint\n if (constraints.availability) {\n const { uptime, gracefulDegradation } = constraints.availability;\n\n if (!uptime || typeof uptime !== 'string') {\n errors.push('Availability constraint must have an uptime value');\n } else if (!/^\\d+(\\.\\d+)?%$/.test(uptime)) {\n errors.push(`Invalid uptime format: \"${uptime}\". Use format like \"99.9%\"`);\n }\n\n if (gracefulDegradation !== undefined && typeof gracefulDegradation !== 'boolean') {\n errors.push('Availability gracefulDegradation must be a boolean');\n }\n }\n}\n\n/**\n * Validate reactivity configuration\n */\nfunction validateReactivity(\n reactivity: ReactivityConfig,\n shape: ShapeDefinition,\n errors: string[],\n warnings: string[]\n): void {\n const allFields = new Set<string>();\n collectFieldPaths(shape, '', allFields);\n\n // Validate realtime fields\n if (reactivity.realtime) {\n if (!Array.isArray(reactivity.realtime)) {\n errors.push('Reactivity realtime must be an array of field paths');\n } else {\n for (const field of reactivity.realtime) {\n if (typeof field !== 'string') {\n errors.push('Realtime field must be a string');\n } else if (!allFields.has(field)) {\n warnings.push(`Realtime field \"${field}\" does not exist in shape`);\n }\n }\n }\n }\n\n // Validate static fields\n if (reactivity.static) {\n if (!Array.isArray(reactivity.static)) {\n errors.push('Reactivity static must be an array of field paths');\n } else {\n for (const field of reactivity.static) {\n if (typeof field !== 'string') {\n errors.push('Static field must be a string');\n } else if (!allFields.has(field)) {\n warnings.push(`Static field \"${field}\" does not exist in shape`);\n }\n }\n }\n }\n\n // Validate polling config\n if (reactivity.polling) {\n if (!Array.isArray(reactivity.polling)) {\n errors.push('Reactivity polling must be an array');\n } else {\n for (const config of reactivity.polling) {\n if (!config.field || typeof config.field !== 'string') {\n errors.push('Polling config must have a field property');\n } else if (!allFields.has(config.field)) {\n warnings.push(`Polling field \"${config.field}\" does not exist in shape`);\n }\n\n if (!config.interval || typeof config.interval !== 'string') {\n errors.push('Polling config must have an interval property');\n } else if (!/^\\d+(ms|s|m)$/.test(config.interval)) {\n errors.push(\n `Invalid polling interval format: \"${config.interval}\". Use format like \"30s\" or \"5m\"`\n );\n }\n }\n }\n }\n\n // Validate event-driven config\n if (reactivity.eventDriven) {\n if (!Array.isArray(reactivity.eventDriven)) {\n errors.push('Reactivity eventDriven must be an array');\n } else {\n for (const config of reactivity.eventDriven) {\n if (!config.field || typeof config.field !== 'string') {\n errors.push('EventDriven config must have a field property');\n } else if (!allFields.has(config.field)) {\n warnings.push(`EventDriven field \"${config.field}\" does not exist in shape`);\n }\n\n if (!config.on || !Array.isArray(config.on)) {\n errors.push('EventDriven config must have an \"on\" array of event names');\n } else if (config.on.length === 0) {\n warnings.push(`EventDriven config for \"${config.field}\" has no events`);\n }\n }\n }\n }\n}\n\n/**\n * Validate versioning configuration\n */\nfunction validateVersioning(\n versioning: VersioningConfig,\n errors: string[],\n warnings: string[]\n): void {\n if (!versioning.version || typeof versioning.version !== 'string') {\n errors.push('Versioning must have a version string');\n } else if (!/^\\d+\\.\\d+\\.\\d+$/.test(versioning.version)) {\n warnings.push(`Version \"${versioning.version}\" should follow semver format (e.g., \"1.0.0\")`);\n }\n\n if (versioning.deprecated && !Array.isArray(versioning.deprecated)) {\n errors.push('Versioning deprecated must be an array of field paths');\n }\n\n if (versioning.migration && typeof versioning.migration !== 'function') {\n errors.push('Versioning migration must be a function');\n }\n}\n\n/**\n * Helper to collect all field paths from shape\n */\nfunction collectFieldPaths(shape: ShapeDefinition, prefix: string, result: Set<string>): void {\n for (const [key, value] of Object.entries(shape)) {\n const path = prefix ? `${prefix}.${key}` : key;\n result.add(path);\n\n if (\n typeof value === 'object' &&\n value !== null &&\n !('_brand' in value) &&\n typeof value !== 'string'\n ) {\n collectFieldPaths(value as ShapeDefinition, path, result);\n }\n }\n}\n","import type { Contract, ShapeDefinition, TypeDefinition } from '@reactive-contracts/core';\nimport type { LatencyAnalysisResult } from '../types.js';\n\n/**\n * Analyze latency constraints of a contract\n */\nexport function analyzeLatency(contract: Contract): LatencyAnalysisResult {\n const { definition } = contract;\n const suggestions: string[] = [];\n\n // If no latency constraint is specified, provide a suggestion\n if (!definition.constraints?.latency) {\n suggestions.push('Consider adding a latency constraint to ensure performance SLAs');\n return {\n status: 'ok',\n suggestions,\n };\n }\n\n const { max: maxLatency, fallback } = definition.constraints.latency;\n\n // Parse latency value\n const latencyMs = parseLatencyToMs(maxLatency);\n\n if (latencyMs === null) {\n return {\n status: 'error',\n message: `Invalid latency format: ${maxLatency}`,\n suggestions: ['Use format like \"100ms\", \"1s\", or \"1m\"'],\n };\n }\n\n // Analyze the latency requirement\n const analysis = analyzeLatencyRequirement(latencyMs);\n\n // Check if fallback strategy is appropriate\n if (!fallback) {\n suggestions.push('Consider specifying a fallback strategy (cachedVersion, degraded, or error)');\n }\n\n // Provide recommendations based on latency target\n if (latencyMs < 50) {\n suggestions.push(\n 'Very aggressive latency target (<50ms). Consider edge caching or CDN for static data.'\n );\n } else if (latencyMs < 100) {\n suggestions.push(\n 'Moderate latency target (<100ms). Ensure database queries are optimized and indexed.'\n );\n } else if (latencyMs > 1000) {\n suggestions.push(\n 'High latency tolerance (>1s). Consider if this provides good user experience.'\n );\n }\n\n // Check for derived fields that might impact latency\n if (hasComplexDerivations(definition.shape)) {\n suggestions.push(\n 'Contract contains derived fields. Consider computing these at edge or origin for better performance.'\n );\n }\n\n // Check reactivity modes that might impact latency\n if (definition.reactivity?.realtime && definition.reactivity.realtime.length > 0) {\n suggestions.push(\n 'Realtime fields require WebSocket connections. Ensure your infrastructure supports this.'\n );\n }\n\n return {\n status: analysis.status,\n estimated: analysis.estimated,\n message: analysis.message,\n suggestions,\n };\n}\n\n/**\n * Parse latency string to milliseconds\n */\nfunction parseLatencyToMs(latency: string): number | null {\n const match = latency.match(/^(\\d+)(ms|s|m)$/);\n if (!match || !match[1] || !match[2]) return null;\n\n const value = parseInt(match[1], 10);\n const unit = match[2];\n\n switch (unit) {\n case 'ms':\n return value;\n case 's':\n return value * 1000;\n case 'm':\n return value * 60 * 1000;\n default:\n return null;\n }\n}\n\n/**\n * Analyze latency requirement and provide status\n */\nfunction analyzeLatencyRequirement(latencyMs: number): {\n status: 'ok' | 'warning' | 'error';\n estimated?: string;\n message?: string;\n} {\n // Simple heuristic-based analysis for MVP\n // In a real implementation, this would analyze the actual backend capabilities\n\n if (latencyMs < 10) {\n return {\n status: 'error',\n estimated: 'Typically 50-100ms for database queries',\n message: 'Latency target <10ms is extremely difficult to achieve consistently',\n };\n }\n\n if (latencyMs < 50) {\n return {\n status: 'warning',\n estimated: 'Requires edge caching or CDN',\n message: 'Latency target <50ms requires careful optimization',\n };\n }\n\n if (latencyMs <= 200) {\n return {\n status: 'ok',\n estimated: 'Achievable with optimized queries and caching',\n message: 'Latency target is reasonable for most applications',\n };\n }\n\n if (latencyMs <= 1000) {\n return {\n status: 'ok',\n estimated: 'Easily achievable with standard backend',\n message: 'Latency target is conservative and should be easy to meet',\n };\n }\n\n return {\n status: 'warning',\n estimated: 'Very high tolerance',\n message: 'Consider if this latency provides acceptable user experience',\n };\n}\n\n/**\n * Check if shape contains complex derived fields\n */\nfunction hasComplexDerivations(\n shape: ShapeDefinition | TypeDefinition | null | undefined\n): boolean {\n if (!shape || typeof shape !== 'object') {\n return false;\n }\n\n for (const value of Object.values(shape)) {\n if (typeof value === 'object' && value !== null) {\n if ('_brand' in value && value._brand === 'DerivedField') {\n return true;\n }\n if (hasComplexDerivations(value)) {\n return true;\n }\n }\n }\n\n return false;\n}\n","import type { Contract, ShapeDefinition, TypeDefinition } from '@reactive-contracts/core';\nimport { writeFile, mkdir } from 'fs/promises';\nimport { dirname } from 'path';\n\n/**\n * Generate TypeScript types for frontend\n */\nexport async function generateFrontendTypes(contract: Contract, outputPath: string): Promise<void> {\n const { definition } = contract;\n const typeName = definition.name;\n\n // Generate TypeScript type definitions\n const typeDefinitions = generateTypeDefinitions(definition.shape, `${typeName}Shape`);\n\n // Generate contract status types\n const content = `/**\n * Auto-generated types for ${typeName} contract\n * DO NOT EDIT - This file is generated by @reactive-contracts/compiler\n */\n\nimport type { ContractStatus } from '@reactive-contracts/core';\n\n${typeDefinitions}\n\n/**\n * Parameters for ${typeName} contract\n */\nexport interface ${typeName}Params {\n // Add your params here based on contract requirements\n [key: string]: unknown;\n}\n\n/**\n * Full result type for ${typeName} contract\n */\nexport interface ${typeName}Result {\n data: ${typeName}Shape;\n status: ContractStatus;\n metadata: {\n executionTime: number;\n cacheHit: boolean;\n derivedAt: 'client' | 'edge' | 'origin';\n };\n}\n\n/**\n * Contract intent: ${definition.intent}\n */\nexport const ${typeName}Intent = '${definition.intent}' as const;\n`;\n\n // Ensure directory exists\n await mkdir(dirname(outputPath), { recursive: true });\n\n // Write to file\n await writeFile(outputPath, content, 'utf-8');\n}\n\n/**\n * Generate resolver template for backend\n */\nexport async function generateBackendResolver(\n contract: Contract,\n outputPath: string\n): Promise<void> {\n const { definition } = contract;\n const typeName = definition.name;\n\n // Generate shape type\n const shapeType = generateTypeDefinitions(definition.shape, `${typeName}ResolverShape`);\n\n // Generate resolver template\n const content = `/**\n * Auto-generated resolver template for ${typeName} contract\n * Generated by @reactive-contracts/compiler\n *\n * Intent: ${definition.intent}\n */\n\nimport { implementContract } from '@reactive-contracts/server';\nimport type { Contract } from '@reactive-contracts/core';\nimport type { ResolverContext } from '@reactive-contracts/server';\n\n${shapeType}\n\n/**\n * Implement the ${typeName} contract resolver\n *\n * This function should return data matching the contract shape.\n * Derived fields will be computed automatically - don't include them.\n */\nexport const ${typeName}Resolver = implementContract(\n // Import your contract definition here\n {} as Contract, // Replace with your contract\n {\n async resolve(params: Record<string, unknown>, context: ResolverContext): Promise<${typeName}ResolverShape> {\n // TODO: Implement your data fetching logic here\n\n // Example:\n // const data = await db.query(...);\n // return {\n // // Map your data to match the contract shape\n // };\n\n throw new Error('${typeName}Resolver not implemented yet');\n },\n\n // Optional: Configure caching\n cache: {\n ttl: '5m',\n staleWhileRevalidate: '1h',\n tags: (params) => [\\`${typeName.toLowerCase()}:\\${params.id}\\`],\n },\n }\n);\n`;\n\n // Ensure directory exists\n await mkdir(dirname(outputPath), { recursive: true });\n\n // Write to file\n await writeFile(outputPath, content, 'utf-8');\n}\n\n/**\n * Generate runtime negotiator\n */\nexport async function generateRuntimeNegotiator(\n contract: Contract,\n outputPath: string\n): Promise<void> {\n const { definition } = contract;\n const typeName = definition.name;\n\n const content = `/**\n * Auto-generated runtime negotiator for ${typeName} contract\n * DO NOT EDIT - This file is generated by @reactive-contracts/compiler\n */\n\nimport type { Contract } from '@reactive-contracts/core';\n\n/**\n * Runtime negotiator for ${typeName}\n * Handles SLA monitoring, fallback logic, and performance tracking\n */\nexport class ${typeName}Negotiator {\n private contract: Contract;\n private metrics: {\n executionTime: number[];\n cacheHits: number;\n cacheMisses: number;\n } = {\n executionTime: [],\n cacheHits: 0,\n cacheMisses: 0,\n };\n\n constructor(contract: Contract) {\n this.contract = contract;\n }\n\n /**\n * Execute contract with SLA monitoring\n */\n async execute<TData>(\n resolver: () => Promise<TData>,\n options?: {\n useCache?: boolean;\n timeout?: number;\n }\n ): Promise<{\n data: TData;\n status: {\n latency: 'normal' | 'degraded' | 'violated';\n freshness: 'fresh' | 'stale' | 'expired';\n availability: 'available' | 'degraded' | 'unavailable';\n };\n metadata: {\n executionTime: number;\n cacheHit: boolean;\n derivedAt: 'client' | 'edge' | 'origin';\n };\n }> {\n const startTime = performance.now();\n\n try {\n // Execute resolver\n const data = await resolver();\n const executionTime = performance.now() - startTime;\n\n // Track metrics\n this.metrics.executionTime.push(executionTime);\n if (options?.useCache) {\n this.metrics.cacheHits++;\n } else {\n this.metrics.cacheMisses++;\n }\n\n // Determine latency status\n const maxLatency = this.getMaxLatency();\n const latencyStatus = this.evaluateLatency(executionTime, maxLatency);\n\n return {\n data,\n status: {\n latency: latencyStatus,\n freshness: 'fresh',\n availability: 'available',\n },\n metadata: {\n executionTime,\n cacheHit: options?.useCache ?? false,\n derivedAt: 'origin',\n },\n };\n } catch (error) {\n // Handle fallback based on contract constraints\n throw error;\n }\n }\n\n /**\n * Get metrics for monitoring\n */\n getMetrics() {\n const avgExecutionTime =\n this.metrics.executionTime.length > 0\n ? this.metrics.executionTime.reduce((a, b) => a + b, 0) / this.metrics.executionTime.length\n : 0;\n\n return {\n averageExecutionTime: avgExecutionTime,\n p95ExecutionTime: this.calculateP95(),\n cacheHitRate:\n this.metrics.cacheHits / (this.metrics.cacheHits + this.metrics.cacheMisses) || 0,\n totalExecutions: this.metrics.executionTime.length,\n };\n }\n\n private getMaxLatency(): number {\n const latency = this.contract.definition.constraints?.latency?.max;\n if (!latency) return Infinity;\n\n // Simple parsing for MVP\n const match = latency.match(/^(\\\\d+)(ms|s|m)$/);\n if (!match) return Infinity;\n\n const value = parseInt(match[1], 10);\n const unit = match[2];\n\n switch (unit) {\n case 'ms': return value;\n case 's': return value * 1000;\n case 'm': return value * 60 * 1000;\n default: return Infinity;\n }\n }\n\n private evaluateLatency(\n executionTime: number,\n maxLatency: number\n ): 'normal' | 'degraded' | 'violated' {\n if (executionTime <= maxLatency) {\n return 'normal';\n } else if (executionTime <= maxLatency * 1.5) {\n return 'degraded';\n } else {\n return 'violated';\n }\n }\n\n private calculateP95(): number {\n if (this.metrics.executionTime.length === 0) return 0;\n\n const sorted = [...this.metrics.executionTime].sort((a, b) => a - b);\n const index = Math.floor(sorted.length * 0.95);\n return sorted[index];\n }\n}\n\n/**\n * Create a new negotiator instance\n */\nexport function create${typeName}Negotiator(contract: Contract): ${typeName}Negotiator {\n return new ${typeName}Negotiator(contract);\n}\n`;\n\n // Ensure directory exists\n await mkdir(dirname(outputPath), { recursive: true });\n\n // Write to file\n await writeFile(outputPath, content, 'utf-8');\n}\n\n/**\n * Generate TypeScript type definitions from shape\n */\nfunction generateTypeDefinitions(shape: ShapeDefinition, typeName: string): string {\n const fields = generateShapeFields(shape, 0);\n\n return `export interface ${typeName} {\n${fields}\n}`;\n}\n\n/**\n * Recursively generate shape fields\n */\nfunction generateShapeFields(shape: ShapeDefinition, indent: number): string {\n const indentStr = ' '.repeat(indent + 1);\n const lines: string[] = [];\n\n for (const [key, value] of Object.entries(shape)) {\n const typeStr = generateTypeString(value, indent + 1);\n lines.push(`${indentStr}${key}: ${typeStr};`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate TypeScript type string from type definition\n */\nfunction generateTypeString(type: TypeDefinition, indent: number): string {\n if (typeof type === 'string') {\n // Primitive or URL type\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'Date':\n return 'Date';\n case 'null':\n return 'null';\n case 'undefined':\n return 'undefined';\n default:\n if (type === 'URL' || type.startsWith('URL<')) {\n return 'string'; // URLs are represented as strings\n }\n return 'any';\n }\n } else if (typeof type === 'object' && type !== null) {\n // Check if it's a DerivedField\n if ('_brand' in type && type._brand === 'DerivedField') {\n // For derived fields, we don't know the return type at compile time\n // In a real implementation, we'd analyze the function\n return 'any';\n } else {\n // Nested shape\n const fields = generateShapeFields(type as ShapeDefinition, indent);\n const indentStr = ' '.repeat(indent);\n return `{\\n${fields}\\n${indentStr}}`;\n }\n }\n\n return 'any';\n}\n"]}