@hyperscale0/hsx 1.0.0-rc.1 → 1.0.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/README.md +4 -2
  3. package/bin/hsx.ts +2 -0
  4. package/dist/bin/hsx.js +2 -0
  5. package/dist/bin/hsx.js.map +1 -1
  6. package/dist/src/ast.d.ts +6 -0
  7. package/dist/src/ast.d.ts.map +1 -1
  8. package/dist/src/ast.js +24 -0
  9. package/dist/src/ast.js.map +1 -1
  10. package/dist/src/cli.d.ts +3 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +25 -5
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/compile.d.ts +1 -3
  15. package/dist/src/compile.d.ts.map +1 -1
  16. package/dist/src/compile.js +1 -2
  17. package/dist/src/compile.js.map +1 -1
  18. package/dist/src/emit.d.ts +1 -2
  19. package/dist/src/emit.d.ts.map +1 -1
  20. package/dist/src/emit.js +1 -223
  21. package/dist/src/emit.js.map +1 -1
  22. package/dist/src/index.d.ts +2 -1
  23. package/dist/src/index.d.ts.map +1 -1
  24. package/dist/src/index.js +2 -0
  25. package/dist/src/index.js.map +1 -1
  26. package/dist/src/lsp/server.d.ts +32 -0
  27. package/dist/src/lsp/server.d.ts.map +1 -0
  28. package/dist/src/lsp/server.js +391 -0
  29. package/dist/src/lsp/server.js.map +1 -0
  30. package/dist/src/modules.d.ts +2 -0
  31. package/dist/src/modules.d.ts.map +1 -1
  32. package/dist/src/modules.js +7 -11
  33. package/dist/src/modules.js.map +1 -1
  34. package/dist/src/std-bundle.d.ts +2 -0
  35. package/dist/src/std-bundle.d.ts.map +1 -0
  36. package/dist/src/std-bundle.js +88 -0
  37. package/dist/src/std-bundle.js.map +1 -0
  38. package/dist/src/std-library.d.ts +5 -0
  39. package/dist/src/std-library.d.ts.map +1 -0
  40. package/dist/src/std-library.js +9 -0
  41. package/dist/src/std-library.js.map +1 -0
  42. package/dist/src/version.d.ts +1 -1
  43. package/dist/src/version.d.ts.map +1 -1
  44. package/dist/src/version.js +1 -1
  45. package/dist/src/version.js.map +1 -1
  46. package/docs/README.md +3 -0
  47. package/docs/guide/01-first-program.md +1 -1
  48. package/docs/llms-full.txt +7 -6
  49. package/docs/llms.txt +2 -2
  50. package/docs/playground.md +54 -0
  51. package/docs/reference/cli.md +5 -3
  52. package/docs/reference/diagnostics.md +1 -1
  53. package/docs/reference/grammar.md +1 -1
  54. package/docs/reference/std/advance.md +1 -1
  55. package/docs/reference/std/cancellable_booking.md +1 -1
  56. package/docs/reference/std/captured_payment.md +1 -1
  57. package/docs/reference/std/conditional_disbursement.md +1 -1
  58. package/docs/reference/std/credit_facility.md +1 -1
  59. package/docs/reference/std/held_payment.md +1 -1
  60. package/docs/reference/std/instant_transfer.md +1 -1
  61. package/docs/reference/std/metered.md +1 -1
  62. package/docs/reference/std/pooled_split.md +1 -1
  63. package/docs/reference/std/premium_forward.md +1 -1
  64. package/docs/reference/std/reconciled_payout.md +1 -1
  65. package/docs/reference/std/recurring_collection.md +1 -1
  66. package/docs/reference/std/rotating_pool.md +1 -1
  67. package/docs/reference/std/scheduled.md +1 -1
  68. package/docs/reference/std/security_deposit.md +1 -1
  69. package/docs/reference/std/settlement_batch.md +1 -1
  70. package/docs/reference/std/swap.md +1 -1
  71. package/docs/reference/std/threshold_pool.md +1 -1
  72. package/docs/reference/std/weighted_distribution.md +1 -1
  73. package/docs/reference/types.md +1 -1
  74. package/docs/reference/udl-output.md +2 -3
  75. package/examples/02-imports-and-archetypes/README.md +1 -4
  76. package/examples/04-complete-product/README.md +0 -3
  77. package/package.json +11 -3
  78. package/skills/hsx/SKILL.md +1 -1
  79. package/src/ast.ts +30 -0
  80. package/src/cli.ts +28 -9
  81. package/src/compile.ts +1 -4
  82. package/src/emit.ts +2 -248
  83. package/src/index.ts +8 -6
  84. package/src/lsp/server.ts +460 -0
  85. package/src/modules.ts +12 -10
  86. package/src/std-bundle.ts +91 -0
  87. package/src/std-library.ts +12 -0
  88. package/src/version.ts +1 -1
@@ -0,0 +1,460 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { dirname, isAbsolute, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { lineIndex, type LineIndex } from "../ast.ts";
5
+ import { format } from "../format.ts";
6
+ import type { HsxCompilerHost, ModuleSource } from "../modules.ts";
7
+ import { resolveProgramModules } from "../modules.ts";
8
+ import { parseProgram } from "../parse.ts";
9
+ import { checkGeneralProgram } from "../typecheck.ts";
10
+
11
+ export interface LspPosition {
12
+ readonly character: number;
13
+ readonly line: number;
14
+ }
15
+
16
+ export interface LspRange {
17
+ readonly end: LspPosition;
18
+ readonly start: LspPosition;
19
+ }
20
+
21
+ export interface LspDiagnostic {
22
+ readonly code?: string;
23
+ readonly message: string;
24
+ readonly range: LspRange;
25
+ readonly severity: 1 | 2;
26
+ readonly source: "hsx";
27
+ }
28
+
29
+ export interface LspServerOptions {
30
+ readonly host?: HsxCompilerHost;
31
+ readonly onExit?: (code: number) => void;
32
+ }
33
+
34
+ export interface LspServer {
35
+ readonly stop: () => void;
36
+ }
37
+
38
+ export function offsetToPosition(
39
+ index: LineIndex,
40
+ offset: number,
41
+ ): LspPosition {
42
+ const clamped = Math.max(0, Math.min(offset, index.length));
43
+ let low = 0;
44
+ let high = index.starts.length - 1;
45
+ while (low < high) {
46
+ const middle = Math.floor((low + high + 1) / 2);
47
+ if ((index.starts[middle] as number) <= clamped) low = middle;
48
+ else high = middle - 1;
49
+ }
50
+ const lineStart = index.starts[low] as number;
51
+ return {
52
+ character: clamped - lineStart,
53
+ line: low,
54
+ };
55
+ }
56
+
57
+ export function spanToRange(
58
+ index: LineIndex,
59
+ span: { readonly end: number; readonly start: number },
60
+ ): LspRange {
61
+ return {
62
+ end: offsetToPosition(index, Math.max(span.start, span.end)),
63
+ start: offsetToPosition(index, span.start),
64
+ };
65
+ }
66
+
67
+ export function createHostForUri(
68
+ uri: string,
69
+ fallbackHost?: HsxCompilerHost,
70
+ ): HsxCompilerHost {
71
+ let docDir: string | undefined;
72
+ try {
73
+ if (uri.startsWith("file://")) {
74
+ docDir = dirname(fileURLToPath(uri));
75
+ }
76
+ } catch {
77
+ docDir = undefined;
78
+ }
79
+
80
+ return {
81
+ resolveModule(specifier: string, from: string): ModuleSource | undefined {
82
+ if (fallbackHost?.resolveModule) {
83
+ const custom = fallbackHost.resolveModule(specifier, from);
84
+ if (custom) return custom;
85
+ }
86
+ if (!docDir) return undefined;
87
+ const baseDir = from
88
+ ? isAbsolute(from)
89
+ ? dirname(from)
90
+ : resolve(docDir, dirname(from))
91
+ : docDir;
92
+ const candidates = [
93
+ resolve(baseDir, specifier),
94
+ resolve(baseDir, `${specifier}.hsx`),
95
+ resolve(docDir, specifier),
96
+ resolve(docDir, `${specifier}.hsx`),
97
+ ];
98
+ for (const candidate of candidates) {
99
+ if (existsSync(candidate)) {
100
+ try {
101
+ const stat = statSync(candidate);
102
+ if (stat.isFile()) {
103
+ return {
104
+ name: candidate,
105
+ source: readFileSync(candidate, "utf8"),
106
+ };
107
+ }
108
+ } catch {
109
+ // Ignore filesystem errors and check subsequent candidates.
110
+ }
111
+ }
112
+ }
113
+ return undefined;
114
+ },
115
+ };
116
+ }
117
+
118
+ interface JsonRpcMessage {
119
+ readonly id?: number | string;
120
+ readonly jsonrpc: "2.0";
121
+ readonly method?: string;
122
+ readonly params?: any;
123
+ }
124
+
125
+ export function startLspServer(
126
+ input: NodeJS.ReadableStream,
127
+ output: NodeJS.WritableStream,
128
+ options: LspServerOptions = {},
129
+ ): LspServer {
130
+ const documents = new Map<string, string>();
131
+ let isInitialized = false;
132
+ let isShutdown = false;
133
+ let buffer = Buffer.alloc(0);
134
+
135
+ const send = (message: unknown): void => {
136
+ const json = JSON.stringify(message);
137
+ const bytes = Buffer.from(json, "utf8");
138
+ output.write(`Content-Length: ${bytes.length}\r\n\r\n${json}`);
139
+ };
140
+
141
+ const validateAndPublish = (uri: string, source: string): void => {
142
+ const lineIdx = lineIndex(source);
143
+ const diagnostics: LspDiagnostic[] = [];
144
+
145
+ const parsed = parseProgram(source);
146
+ for (const diag of parsed.diagnostics) {
147
+ diagnostics.push({
148
+ ...(diag.code ? { code: diag.code } : {}),
149
+ message: diag.message,
150
+ range: spanToRange(lineIdx, diag.span),
151
+ severity: 1,
152
+ source: "hsx",
153
+ });
154
+ }
155
+
156
+ if (parsed.diagnostics.length === 0) {
157
+ const host = createHostForUri(uri, options.host);
158
+ const resolved = resolveProgramModules(parsed.program, host);
159
+ if (!resolved.ok) {
160
+ for (const issue of resolved.issues) {
161
+ diagnostics.push({
162
+ code: issue.code,
163
+ message: issue.message,
164
+ range: spanToRange(lineIdx, issue.span),
165
+ severity: 1,
166
+ source: "hsx",
167
+ });
168
+ }
169
+ } else {
170
+ const checked = checkGeneralProgram(resolved.program);
171
+ for (const diag of checked.diagnostics) {
172
+ if (!resolved.origins.has(diag.span)) {
173
+ diagnostics.push({
174
+ code: diag.code,
175
+ message: diag.message,
176
+ range: spanToRange(lineIdx, diag.span),
177
+ severity: diag.severity === "warning" ? 2 : 1,
178
+ source: "hsx",
179
+ });
180
+ }
181
+ }
182
+ }
183
+ }
184
+
185
+ send({
186
+ jsonrpc: "2.0",
187
+ method: "textDocument/publishDiagnostics",
188
+ params: {
189
+ diagnostics,
190
+ uri,
191
+ },
192
+ });
193
+ };
194
+
195
+ const handleMessage = (msg: JsonRpcMessage): void => {
196
+ const { id, method, params } = msg;
197
+
198
+ // Requests (id is present)
199
+ if (id !== undefined) {
200
+ if (isShutdown) {
201
+ send({
202
+ error: {
203
+ code: -32600,
204
+ message: "Invalid request: server is shutting down",
205
+ },
206
+ id,
207
+ jsonrpc: "2.0",
208
+ });
209
+ return;
210
+ }
211
+
212
+ if (!isInitialized) {
213
+ if (method !== "initialize") {
214
+ send({
215
+ error: {
216
+ code: -32002,
217
+ message: "Server not initialized",
218
+ },
219
+ id,
220
+ jsonrpc: "2.0",
221
+ });
222
+ return;
223
+ }
224
+
225
+ isInitialized = true;
226
+ send({
227
+ id,
228
+ jsonrpc: "2.0",
229
+ result: {
230
+ capabilities: {
231
+ documentFormattingProvider: true,
232
+ textDocumentSync: 1,
233
+ },
234
+ serverInfo: {
235
+ name: "hsx-lsp",
236
+ version: "1.0.0",
237
+ },
238
+ },
239
+ });
240
+ return;
241
+ }
242
+
243
+ if (method === "initialize") {
244
+ send({
245
+ id,
246
+ jsonrpc: "2.0",
247
+ result: {
248
+ capabilities: {
249
+ documentFormattingProvider: true,
250
+ textDocumentSync: 1,
251
+ },
252
+ serverInfo: {
253
+ name: "hsx-lsp",
254
+ version: "1.0.0",
255
+ },
256
+ },
257
+ });
258
+ return;
259
+ }
260
+
261
+ if (method === "shutdown") {
262
+ isShutdown = true;
263
+ send({
264
+ id,
265
+ jsonrpc: "2.0",
266
+ result: null,
267
+ });
268
+ return;
269
+ }
270
+
271
+ if (method === "textDocument/formatting") {
272
+ const uri = params?.textDocument?.uri;
273
+ const source = uri ? documents.get(uri) : undefined;
274
+ if (!source) {
275
+ send({ id, jsonrpc: "2.0", result: null });
276
+ return;
277
+ }
278
+ const formatted = format(source);
279
+ if (!formatted.ok) {
280
+ send({ id, jsonrpc: "2.0", result: null });
281
+ return;
282
+ }
283
+ if (formatted.formatted === source) {
284
+ send({ id, jsonrpc: "2.0", result: [] });
285
+ return;
286
+ }
287
+ const lines = lineIndex(source);
288
+ send({
289
+ id,
290
+ jsonrpc: "2.0",
291
+ result: [
292
+ {
293
+ newText: formatted.formatted,
294
+ range: {
295
+ end: offsetToPosition(lines, source.length),
296
+ start: { character: 0, line: 0 },
297
+ },
298
+ },
299
+ ],
300
+ });
301
+ return;
302
+ }
303
+
304
+ send({
305
+ error: {
306
+ code: -32601,
307
+ message: `Method not found: ${method ?? "unknown"}`,
308
+ },
309
+ id,
310
+ jsonrpc: "2.0",
311
+ });
312
+ return;
313
+ }
314
+
315
+ // Notifications (id is undefined)
316
+ if (method === "exit") {
317
+ const code = isShutdown ? 0 : 1;
318
+ if (options.onExit) {
319
+ options.onExit(code);
320
+ } else {
321
+ process.exit(code);
322
+ }
323
+ return;
324
+ }
325
+
326
+ if (isShutdown || !isInitialized) {
327
+ return;
328
+ }
329
+
330
+ if (method === "initialized") {
331
+ return;
332
+ }
333
+
334
+ if (method === "textDocument/didOpen") {
335
+ const doc = params?.textDocument;
336
+ if (doc?.uri && typeof doc.text === "string") {
337
+ documents.set(doc.uri, doc.text);
338
+ validateAndPublish(doc.uri, doc.text);
339
+ }
340
+ return;
341
+ }
342
+
343
+ if (method === "textDocument/didChange") {
344
+ const uri = params?.textDocument?.uri;
345
+ const changes = params?.contentChanges;
346
+ if (!uri || !Array.isArray(changes) || changes.length === 0) {
347
+ // Empty contentChanges keeps the document and republishes nothing.
348
+ return;
349
+ }
350
+ // Full sync only; an incremental entry would replace the document with a fragment.
351
+ const hasIncremental = changes.some(
352
+ (change: any) =>
353
+ change && typeof change === "object" && "range" in change,
354
+ );
355
+ if (hasIncremental) {
356
+ return;
357
+ }
358
+ const lastChange = changes[changes.length - 1];
359
+ if (lastChange && typeof lastChange.text === "string") {
360
+ documents.set(uri, lastChange.text);
361
+ validateAndPublish(uri, lastChange.text);
362
+ }
363
+ return;
364
+ }
365
+
366
+ if (method === "textDocument/didClose") {
367
+ const uri = params?.textDocument?.uri;
368
+ if (uri) {
369
+ documents.delete(uri);
370
+ send({
371
+ jsonrpc: "2.0",
372
+ method: "textDocument/publishDiagnostics",
373
+ params: {
374
+ diagnostics: [],
375
+ uri,
376
+ },
377
+ });
378
+ }
379
+ return;
380
+ }
381
+ };
382
+
383
+ const processBuffer = (): void => {
384
+ while (true) {
385
+ const headerEnd = buffer.indexOf("\r\n\r\n");
386
+ if (headerEnd === -1) break;
387
+ const headerText = buffer.subarray(0, headerEnd).toString("ascii");
388
+ const match = /content-length:\s*(\d+)/i.exec(headerText);
389
+ if (!match) {
390
+ buffer = buffer.subarray(headerEnd + 4);
391
+ continue;
392
+ }
393
+ const contentLength = parseInt(match[1] as string, 10);
394
+ if (Number.isNaN(contentLength) || contentLength < 0) {
395
+ buffer = buffer.subarray(headerEnd + 4);
396
+ continue;
397
+ }
398
+ const totalLength = headerEnd + 4 + contentLength;
399
+ if (buffer.length < totalLength) {
400
+ break;
401
+ }
402
+ const bodyBytes = buffer.subarray(headerEnd + 4, totalLength);
403
+ buffer = buffer.subarray(totalLength);
404
+ const bodyStr = bodyBytes.toString("utf8");
405
+ try {
406
+ const msg = JSON.parse(bodyStr) as JsonRpcMessage;
407
+ handleMessage(msg);
408
+ } catch {
409
+ // Ignore unparseable JSON payload.
410
+ }
411
+ }
412
+ };
413
+
414
+ const flushPending = (): void => {
415
+ const headerEnd = buffer.indexOf("\r\n\r\n");
416
+ if (headerEnd !== -1) {
417
+ const bodyStr = buffer
418
+ .subarray(headerEnd + 4)
419
+ .toString("utf8")
420
+ .trim();
421
+ if (bodyStr.length > 0) {
422
+ try {
423
+ const msg = JSON.parse(bodyStr) as JsonRpcMessage;
424
+ handleMessage(msg);
425
+ } catch {
426
+ // Ignore unparseable body.
427
+ }
428
+ }
429
+ }
430
+ };
431
+
432
+ const onData = (chunk: Buffer | string): void => {
433
+ const incoming =
434
+ typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
435
+ buffer = Buffer.concat([buffer, incoming]);
436
+ processBuffer();
437
+ };
438
+
439
+ const onEnd = (): void => {
440
+ processBuffer();
441
+ if (buffer.length > 0) {
442
+ flushPending();
443
+ }
444
+ if (options.onExit) {
445
+ options.onExit(0);
446
+ } else {
447
+ process.exit(0);
448
+ }
449
+ };
450
+
451
+ input.on("data", onData);
452
+ input.on("end", onEnd);
453
+
454
+ return {
455
+ stop(): void {
456
+ input.removeListener("data", onData);
457
+ input.removeListener("end", onEnd);
458
+ },
459
+ };
460
+ }
package/src/modules.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
1
  import type { UdlDocument } from "@hyperscale0/udl";
3
2
  import type {
4
3
  ApplicationScopeDecl,
@@ -10,6 +9,7 @@ import type {
10
9
  } from "./ast.ts";
11
10
  import { lineColIn, lineIndex } from "./ast.ts";
12
11
  import { parseProgram } from "./parse.ts";
12
+ import { bundledStandardLibrary, type StandardLibrary } from "./std-library.ts";
13
13
 
14
14
  export interface ModuleSource {
15
15
  readonly name: string;
@@ -24,6 +24,7 @@ export interface HsxCompilerHost {
24
24
  specifier: string,
25
25
  from: string,
26
26
  ) => ModuleSource | undefined;
27
+ readonly standardLibrary?: StandardLibrary;
27
28
  }
28
29
 
29
30
  export interface ModuleIssue {
@@ -68,7 +69,12 @@ export function resolveProgramModules(
68
69
  );
69
70
  for (const declaration of imports) {
70
71
  const requested = declaration.names.map((name) => name.name);
71
- const sources = standardSources(declaration.from.value, requested);
72
+ const stdLib = host.standardLibrary ?? bundledStandardLibrary;
73
+ const sources = standardSources(
74
+ stdLib,
75
+ declaration.from.value,
76
+ requested,
77
+ );
72
78
  const custom =
73
79
  sources.length === 0
74
80
  ? host.resolveModule?.(declaration.from.value, from)
@@ -421,22 +427,18 @@ function collectTemplatedNameReferences(
421
427
  }
422
428
 
423
429
  function standardSources(
430
+ standardLibrary: StandardLibrary,
424
431
  specifier: string,
425
432
  names: readonly string[],
426
433
  ): ModuleSource[] {
427
434
  if (specifier !== "std/settlements") return [];
428
435
  return names.flatMap((name) => {
429
- const relative = `settlements/${name}.hsx`;
430
- const candidates = [
431
- new URL(`../std/${relative}`, import.meta.url),
432
- new URL(`../../std/${relative}`, import.meta.url),
433
- ];
434
- const url = candidates.find((candidate) => existsSync(candidate));
435
- return url
436
+ const source = standardLibrary.source(specifier, name);
437
+ return source !== undefined
436
438
  ? [
437
439
  {
438
440
  name: `std.settlements.${name}`,
439
- source: readFileSync(url, "utf8"),
441
+ source,
440
442
  },
441
443
  ]
442
444
  : [];