@stryke/capnp 0.3.0 → 0.4.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 (41) hide show
  1. package/bin/capnpc.cjs +1179 -0
  2. package/bin/capnpc.js +1146 -0
  3. package/dist/chunk-LY3GWW4E.js +977 -0
  4. package/dist/chunk-ORA4UQMU.cjs +1 -0
  5. package/dist/chunk-OULCUN6I.js +0 -0
  6. package/dist/chunk-PV3OG5H3.cjs +977 -0
  7. package/dist/chunk-SHUYVCID.js +6 -0
  8. package/dist/chunk-USNT2KNT.cjs +6 -0
  9. package/dist/compile.cjs +7 -0
  10. package/dist/compile.js +7 -0
  11. package/dist/index.cjs +8 -0
  12. package/dist/index.js +8 -0
  13. package/dist/rpc.cjs +103 -0
  14. package/dist/rpc.d.cts +42 -0
  15. package/dist/rpc.d.ts +42 -0
  16. package/dist/rpc.js +103 -0
  17. package/dist/types.cjs +1 -0
  18. package/dist/types.js +1 -0
  19. package/package.json +19 -2
  20. package/dist/bin/capnpc.cjs +0 -11269
  21. package/dist/bin/capnpc.d.cts +0 -6
  22. package/dist/bin/capnpc.d.ts +0 -6
  23. package/dist/bin/capnpc.js +0 -11266
  24. package/dist/chunk-E5KOPL7Q.cjs +0 -6
  25. package/dist/chunk-EK5N4FAF.js +0 -55
  26. package/dist/chunk-IWTVA3JL.cjs +0 -104
  27. package/dist/chunk-QKE2ND5U.js +0 -104
  28. package/dist/chunk-TE2KW23K.cjs +0 -55
  29. package/dist/chunk-UQ2KKHLM.js +0 -6
  30. package/dist/src/compile.cjs +0 -7
  31. package/dist/src/compile.js +0 -7
  32. package/dist/src/index.cjs +0 -13
  33. package/dist/src/index.js +0 -13
  34. package/dist/src/types.cjs +0 -2
  35. package/dist/src/types.js +0 -2
  36. /package/dist/{src/compile.d.cts → compile.d.cts} +0 -0
  37. /package/dist/{src/compile.d.ts → compile.d.ts} +0 -0
  38. /package/dist/{src/index.d.cts → index.d.cts} +0 -0
  39. /package/dist/{src/index.d.ts → index.d.ts} +0 -0
  40. /package/dist/{src/types.d.cts → types.d.cts} +0 -0
  41. /package/dist/{src/types.d.ts → types.d.ts} +0 -0
package/bin/capnpc.js ADDED
@@ -0,0 +1,1146 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+
5
+ // bin/capnpc.ts
6
+ import { writeFatal, writeInfo, writeSuccess } from "@storm-software/config-tools/logger/console";
7
+ import { exitWithError, exitWithSuccess, findWorkspaceRootSafe as findWorkspaceRootSafe2, handleProcess } from "@storm-software/config-tools/utilities";
8
+
9
+ // ../fs/src/list-files.ts
10
+ import defu from "defu";
11
+ import { glob } from "glob";
12
+ var DEFAULT_OPTIONS = {
13
+ dot: true
14
+ };
15
+ async function list(filesGlob, options) {
16
+ return glob(filesGlob, defu(options ?? {}, DEFAULT_OPTIONS));
17
+ }
18
+ __name(list, "list");
19
+ async function listFiles(filesGlob, options) {
20
+ const result = (await list(filesGlob, defu({
21
+ withFileTypes: true
22
+ }, options ?? {}))).filter((ret) => ret.isFile());
23
+ if (!options?.withFileTypes) {
24
+ return result.map((file) => file.fullpath());
25
+ }
26
+ return result;
27
+ }
28
+ __name(listFiles, "listFiles");
29
+
30
+ // ../fs/src/read-file.ts
31
+ import { parse as parseToml } from "@ltd/j-toml";
32
+
33
+ // ../type-checks/src/get-object-tag.ts
34
+ var getObjectTag = /* @__PURE__ */ __name((value) => {
35
+ if (value == null) {
36
+ return value === void 0 ? "[object Undefined]" : "[object Null]";
37
+ }
38
+ return Object.prototype.toString.call(value);
39
+ }, "getObjectTag");
40
+
41
+ // ../type-checks/src/is-plain-object.ts
42
+ var isObjectLike = /* @__PURE__ */ __name((obj) => {
43
+ return typeof obj === "object" && obj !== null;
44
+ }, "isObjectLike");
45
+ var isPlainObject = /* @__PURE__ */ __name((obj) => {
46
+ if (!isObjectLike(obj) || getObjectTag(obj) !== "[object Object]") {
47
+ return false;
48
+ }
49
+ if (Object.getPrototypeOf(obj) === null) {
50
+ return true;
51
+ }
52
+ let proto = obj;
53
+ while (Object.getPrototypeOf(proto) !== null) {
54
+ proto = Object.getPrototypeOf(proto);
55
+ }
56
+ return Object.getPrototypeOf(obj) === proto;
57
+ }, "isPlainObject");
58
+
59
+ // ../type-checks/src/is-object.ts
60
+ var isObject = /* @__PURE__ */ __name((value) => {
61
+ try {
62
+ return typeof value === "object" || Boolean(value) && value?.constructor === Object || isPlainObject(value);
63
+ } catch {
64
+ return false;
65
+ }
66
+ }, "isObject");
67
+
68
+ // ../type-checks/src/is-string.ts
69
+ var isString = /* @__PURE__ */ __name((value) => {
70
+ try {
71
+ return typeof value === "string";
72
+ } catch {
73
+ return false;
74
+ }
75
+ }, "isString");
76
+
77
+ // ../json/src/storm-json.ts
78
+ import { parse as parse2 } from "jsonc-parser";
79
+ import { Buffer as Buffer2 } from "node:buffer";
80
+ import SuperJSON from "superjson";
81
+
82
+ // ../types/src/base.ts
83
+ var EMPTY_STRING = "";
84
+ var $NestedValue = Symbol("NestedValue");
85
+
86
+ // ../json/src/utils/strip-comments.ts
87
+ var singleComment = Symbol("singleComment");
88
+ var multiComment = Symbol("multiComment");
89
+ function stripWithoutWhitespace() {
90
+ return "";
91
+ }
92
+ __name(stripWithoutWhitespace, "stripWithoutWhitespace");
93
+ function stripWithWhitespace(value, start, end) {
94
+ return value.slice(start, end).replace(/\S/g, " ");
95
+ }
96
+ __name(stripWithWhitespace, "stripWithWhitespace");
97
+ function isEscaped(value, quotePosition) {
98
+ let index = quotePosition - 1;
99
+ let backslashCount = 0;
100
+ while (value[index] === "\\") {
101
+ index -= 1;
102
+ backslashCount += 1;
103
+ }
104
+ return Boolean(backslashCount % 2);
105
+ }
106
+ __name(isEscaped, "isEscaped");
107
+ function stripComments(value, { whitespace = true, trailingCommas = false } = {}) {
108
+ if (typeof value !== "string") {
109
+ throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof value}\``);
110
+ }
111
+ const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace;
112
+ let isInsideString = false;
113
+ let isInsideComment = false;
114
+ let offset = 0;
115
+ let buffer = "";
116
+ let result = "";
117
+ let commaIndex = -1;
118
+ for (let index = 0; index < value.length; index++) {
119
+ const currentCharacter = value[index];
120
+ const nextCharacter = value[index + 1];
121
+ if (!isInsideComment && currentCharacter === '"') {
122
+ const escaped = isEscaped(value, index);
123
+ if (!escaped) {
124
+ isInsideString = !isInsideString;
125
+ }
126
+ }
127
+ if (isInsideString) {
128
+ continue;
129
+ }
130
+ if (!isInsideComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "//") {
131
+ buffer += value.slice(offset, index);
132
+ offset = index;
133
+ isInsideComment = singleComment;
134
+ index++;
135
+ } else if (isInsideComment === singleComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "\r\n") {
136
+ index++;
137
+ isInsideComment = false;
138
+ buffer += strip(value, offset, index);
139
+ offset = index;
140
+ } else if (isInsideComment === singleComment && currentCharacter === "\n") {
141
+ isInsideComment = false;
142
+ buffer += strip(value, offset, index);
143
+ offset = index;
144
+ } else if (!isInsideComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "/*") {
145
+ buffer += value.slice(offset, index);
146
+ offset = index;
147
+ isInsideComment = multiComment;
148
+ index++;
149
+ } else if (isInsideComment === multiComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "*/") {
150
+ index++;
151
+ isInsideComment = false;
152
+ buffer += strip(value, offset, index + 1);
153
+ offset = index + 1;
154
+ } else if (trailingCommas && !isInsideComment) {
155
+ if (commaIndex !== -1) {
156
+ if (currentCharacter === "}" || currentCharacter === "]") {
157
+ buffer += value.slice(offset, index);
158
+ result += strip(buffer, 0, 1) + buffer.slice(1);
159
+ buffer = "";
160
+ offset = index;
161
+ commaIndex = -1;
162
+ } else if (currentCharacter !== " " && currentCharacter !== " " && currentCharacter !== "\r" && currentCharacter !== "\n") {
163
+ buffer += value.slice(offset, index);
164
+ offset = index;
165
+ commaIndex = -1;
166
+ }
167
+ } else if (currentCharacter === ",") {
168
+ result += buffer + value.slice(offset, index);
169
+ buffer = "";
170
+ offset = index;
171
+ commaIndex = index;
172
+ }
173
+ }
174
+ }
175
+ return result + buffer + (isInsideComment ? strip(value.slice(offset)) : value.slice(offset));
176
+ }
177
+ __name(stripComments, "stripComments");
178
+
179
+ // ../json/src/utils/parse.ts
180
+ var suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
181
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
182
+ var JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(?:\.\d{1,17})?(?:E[+-]?\d+)?\s*$/i;
183
+ function jsonParseTransform(key, value) {
184
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
185
+ console.warn(`Dropping "${key}" key to prevent prototype pollution.`);
186
+ return;
187
+ }
188
+ return value;
189
+ }
190
+ __name(jsonParseTransform, "jsonParseTransform");
191
+ function parse(value, options = {}) {
192
+ if (typeof value !== "string") {
193
+ return value;
194
+ }
195
+ let stripped = stripComments(value);
196
+ if (stripped[0] === '"' && stripped[stripped.length - 1] === '"' && !stripped.includes("\\")) {
197
+ return stripped.slice(1, -1);
198
+ }
199
+ stripped = stripped.trim();
200
+ if (stripped.length <= 9) {
201
+ switch (stripped.toLowerCase()) {
202
+ case "true": {
203
+ return true;
204
+ }
205
+ case "false": {
206
+ return false;
207
+ }
208
+ case "undefined": {
209
+ return void 0;
210
+ }
211
+ case "null": {
212
+ return null;
213
+ }
214
+ case "nan": {
215
+ return Number.NaN;
216
+ }
217
+ case "infinity": {
218
+ return Number.POSITIVE_INFINITY;
219
+ }
220
+ case "-infinity": {
221
+ return Number.NEGATIVE_INFINITY;
222
+ }
223
+ }
224
+ }
225
+ if (!JsonSigRx.test(stripped)) {
226
+ if (options.strict) {
227
+ throw new Error("Invalid JSON");
228
+ }
229
+ return stripped;
230
+ }
231
+ try {
232
+ if (suspectProtoRx.test(stripped) || suspectConstructorRx.test(stripped)) {
233
+ if (options.strict) {
234
+ throw new Error("Possible prototype pollution");
235
+ }
236
+ return JSON.parse(stripped, jsonParseTransform);
237
+ }
238
+ return JSON.parse(stripped);
239
+ } catch (error) {
240
+ if (options.strict) {
241
+ throw error;
242
+ }
243
+ return value;
244
+ }
245
+ }
246
+ __name(parse, "parse");
247
+
248
+ // ../json/src/utils/parse-error.ts
249
+ import { printParseErrorCode } from "jsonc-parser";
250
+ import { LinesAndColumns } from "lines-and-columns";
251
+
252
+ // ../json/src/utils/code-frames.ts
253
+ var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
254
+ function getMarkerLines(loc, source, opts = {}) {
255
+ const startLoc = {
256
+ column: 0,
257
+ line: -1,
258
+ ...loc.start
259
+ };
260
+ const endLoc = {
261
+ ...startLoc,
262
+ ...loc.end
263
+ };
264
+ const { linesAbove = 2, linesBelow = 3 } = opts || {};
265
+ const startLine = startLoc.line;
266
+ const startColumn = startLoc.column;
267
+ const endLine = endLoc.line;
268
+ const endColumn = endLoc.column;
269
+ let start = Math.max(startLine - (linesAbove + 1), 0);
270
+ let end = Math.min(source.length, endLine + linesBelow);
271
+ if (startLine === -1) {
272
+ start = 0;
273
+ }
274
+ if (endLine === -1) {
275
+ end = source.length;
276
+ }
277
+ const lineDiff = endLine - startLine;
278
+ const markerLines = {};
279
+ if (lineDiff) {
280
+ for (let i = 0; i <= lineDiff; i++) {
281
+ const lineNumber = i + startLine;
282
+ if (!startColumn) {
283
+ markerLines[lineNumber] = true;
284
+ } else if (i === 0) {
285
+ const sourceLength = source[lineNumber - 1]?.length ?? 0;
286
+ markerLines[lineNumber] = [
287
+ startColumn,
288
+ sourceLength - startColumn + 1
289
+ ];
290
+ } else if (i === lineDiff) {
291
+ markerLines[lineNumber] = [
292
+ 0,
293
+ endColumn
294
+ ];
295
+ } else {
296
+ const sourceLength = source[lineNumber - i]?.length ?? 0;
297
+ markerLines[lineNumber] = [
298
+ 0,
299
+ sourceLength
300
+ ];
301
+ }
302
+ }
303
+ } else if (startColumn === endColumn) {
304
+ markerLines[startLine] = startColumn ? [
305
+ startColumn,
306
+ 0
307
+ ] : true;
308
+ } else {
309
+ markerLines[startLine] = [
310
+ startColumn,
311
+ endColumn - startColumn
312
+ ];
313
+ }
314
+ return {
315
+ start,
316
+ end,
317
+ markerLines
318
+ };
319
+ }
320
+ __name(getMarkerLines, "getMarkerLines");
321
+ function codeFrameColumns(rawLines, loc, opts = {}) {
322
+ const lines = rawLines.split(NEWLINE);
323
+ const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
324
+ const numberMaxWidth = String(end).length;
325
+ const highlightedLines = opts.highlight ? opts.highlight(rawLines) : rawLines;
326
+ const frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
327
+ const number = start + 1 + index;
328
+ const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
329
+ const gutter = ` ${paddedNumber} | `;
330
+ const hasMarker = Boolean(markerLines[number] ?? false);
331
+ if (hasMarker) {
332
+ let markerLine = "";
333
+ if (Array.isArray(hasMarker)) {
334
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
335
+ const numberOfMarkers = hasMarker[1] || 1;
336
+ markerLine = [
337
+ "\n ",
338
+ gutter.replace(/\d/g, " "),
339
+ markerSpacing,
340
+ "^".repeat(numberOfMarkers)
341
+ ].join("");
342
+ }
343
+ return [
344
+ ">",
345
+ gutter,
346
+ line,
347
+ markerLine
348
+ ].join("");
349
+ }
350
+ return ` ${gutter}${line}`;
351
+ }).join("\n");
352
+ return frame;
353
+ }
354
+ __name(codeFrameColumns, "codeFrameColumns");
355
+
356
+ // ../json/src/utils/parse-error.ts
357
+ function formatParseError(input, parseError) {
358
+ const { error, offset, length } = parseError;
359
+ const result = new LinesAndColumns(input).locationForIndex(offset);
360
+ let line = result?.line ?? 0;
361
+ let column = result?.column ?? 0;
362
+ line++;
363
+ column++;
364
+ return `${printParseErrorCode(error)} in JSON at ${line}:${column}
365
+ ${codeFrameColumns(input, {
366
+ start: {
367
+ line,
368
+ column
369
+ },
370
+ end: {
371
+ line,
372
+ column: column + length
373
+ }
374
+ })}
375
+ `;
376
+ }
377
+ __name(formatParseError, "formatParseError");
378
+
379
+ // ../type-checks/src/is-number.ts
380
+ var isNumber = /* @__PURE__ */ __name((value) => {
381
+ try {
382
+ return value instanceof Number || typeof value === "number" || Number(value) === value;
383
+ } catch {
384
+ return false;
385
+ }
386
+ }, "isNumber");
387
+
388
+ // ../type-checks/src/is-undefined.ts
389
+ var isUndefined = /* @__PURE__ */ __name((value) => {
390
+ return value === void 0;
391
+ }, "isUndefined");
392
+
393
+ // ../json/src/utils/stringify.ts
394
+ var invalidKeyChars = [
395
+ "@",
396
+ "/",
397
+ "#",
398
+ "$",
399
+ " ",
400
+ ":",
401
+ ";",
402
+ ",",
403
+ ".",
404
+ "!",
405
+ "?",
406
+ "&",
407
+ "=",
408
+ "+",
409
+ "-",
410
+ "*",
411
+ "%",
412
+ "^",
413
+ "~",
414
+ "|",
415
+ "\\",
416
+ '"',
417
+ "'",
418
+ "`",
419
+ "{",
420
+ "}",
421
+ "[",
422
+ "]",
423
+ "(",
424
+ ")",
425
+ "<",
426
+ ">"
427
+ ];
428
+ var stringify = /* @__PURE__ */ __name((value, spacing = 2) => {
429
+ const space = isNumber(spacing) ? " ".repeat(spacing) : spacing;
430
+ switch (value) {
431
+ case null: {
432
+ return "null";
433
+ }
434
+ case void 0: {
435
+ return '"undefined"';
436
+ }
437
+ case true: {
438
+ return "true";
439
+ }
440
+ case false: {
441
+ return "false";
442
+ }
443
+ case Number.POSITIVE_INFINITY: {
444
+ return "infinity";
445
+ }
446
+ case Number.NEGATIVE_INFINITY: {
447
+ return "-infinity";
448
+ }
449
+ }
450
+ if (Array.isArray(value)) {
451
+ return `[${space}${value.map((v) => stringify(v, space)).join(`,${space}`)}${space}]`;
452
+ }
453
+ if (value instanceof Uint8Array) {
454
+ return value.toString();
455
+ }
456
+ switch (typeof value) {
457
+ case "number": {
458
+ return `${value}`;
459
+ }
460
+ case "string": {
461
+ return JSON.stringify(value);
462
+ }
463
+ case "object": {
464
+ const keys = Object.keys(value).filter((key) => !isUndefined(value[key]));
465
+ return `{${space}${keys.map((key) => `${invalidKeyChars.some((invalidKeyChar) => key.includes(invalidKeyChar)) ? `"${key}"` : key}: ${space}${stringify(value[key], space)}`).join(`,${space}`)}${space}}`;
466
+ }
467
+ default:
468
+ return "null";
469
+ }
470
+ }, "stringify");
471
+
472
+ // ../json/src/storm-json.ts
473
+ var StormJSON = class _StormJSON extends SuperJSON {
474
+ static {
475
+ __name(this, "StormJSON");
476
+ }
477
+ static #instance;
478
+ static get instance() {
479
+ if (!_StormJSON.#instance) {
480
+ _StormJSON.#instance = new _StormJSON();
481
+ }
482
+ return _StormJSON.#instance;
483
+ }
484
+ /**
485
+ * Deserialize the given value with superjson using the given metadata
486
+ */
487
+ static deserialize(payload) {
488
+ return _StormJSON.instance.deserialize(payload);
489
+ }
490
+ /**
491
+ * Serialize the given value with superjson
492
+ */
493
+ static serialize(object) {
494
+ return _StormJSON.instance.serialize(object);
495
+ }
496
+ /**
497
+ * Parse the given string value with superjson using the given metadata
498
+ *
499
+ * @param value - The string value to parse
500
+ * @returns The parsed data
501
+ */
502
+ static parse(value) {
503
+ return parse(value);
504
+ }
505
+ /**
506
+ * Serializes the given data to a JSON string.
507
+ * By default the JSON string is formatted with a 2 space indentation to be easy readable.
508
+ *
509
+ * @param value - Object which should be serialized to JSON
510
+ * @param _options - JSON serialize options
511
+ * @returns the formatted JSON representation of the object
512
+ */
513
+ static stringify(value, _options) {
514
+ const customTransformer = _StormJSON.instance.customTransformerRegistry.findApplicable(value);
515
+ let result = value;
516
+ if (customTransformer && customTransformer.isApplicable(value)) {
517
+ result = customTransformer.serialize(result);
518
+ }
519
+ return stringify(result);
520
+ }
521
+ /**
522
+ * Parses the given JSON string and returns the object the JSON content represents.
523
+ * By default javascript-style comments and trailing commas are allowed.
524
+ *
525
+ * @param strData - JSON content as string
526
+ * @param options - JSON parse options
527
+ * @returns Object the JSON content represents
528
+ */
529
+ static parseJson(strData, options) {
530
+ try {
531
+ if (options?.expectComments === false) {
532
+ return _StormJSON.instance.parse(strData);
533
+ }
534
+ } catch {
535
+ }
536
+ const errors = [];
537
+ const opts = {
538
+ allowTrailingComma: true,
539
+ ...options
540
+ };
541
+ const result = parse2(strData, errors, opts);
542
+ if (errors.length > 0 && errors[0]) {
543
+ throw new Error(formatParseError(strData, errors[0]));
544
+ }
545
+ return result;
546
+ }
547
+ /**
548
+ * Register a custom schema with superjson
549
+ *
550
+ * @param name - The name of the schema
551
+ * @param serialize - The function to serialize the schema
552
+ * @param deserialize - The function to deserialize the schema
553
+ * @param isApplicable - The function to check if the schema is applicable
554
+ */
555
+ static register(name, serialize, deserialize, isApplicable) {
556
+ _StormJSON.instance.registerCustom({
557
+ isApplicable,
558
+ serialize,
559
+ deserialize
560
+ }, name);
561
+ }
562
+ /**
563
+ * Register a class with superjson
564
+ *
565
+ * @param classConstructor - The class constructor to register
566
+ */
567
+ static registerClass(classConstructor, options) {
568
+ _StormJSON.instance.registerClass(classConstructor, {
569
+ identifier: isString(options) ? options : options?.identifier || classConstructor.name,
570
+ allowProps: options && isObject(options) && options?.allowProps && Array.isArray(options.allowProps) ? options.allowProps : [
571
+ "__typename"
572
+ ]
573
+ });
574
+ }
575
+ constructor() {
576
+ super({
577
+ dedupe: true
578
+ });
579
+ }
580
+ };
581
+ StormJSON.instance.registerCustom({
582
+ isApplicable: /* @__PURE__ */ __name((v) => Buffer2.isBuffer(v), "isApplicable"),
583
+ serialize: /* @__PURE__ */ __name((v) => v.toString("base64"), "serialize"),
584
+ deserialize: /* @__PURE__ */ __name((v) => Buffer2.from(v, "base64"), "deserialize")
585
+ }, "Bytes");
586
+
587
+ // ../type-checks/src/is-error.ts
588
+ var isError = /* @__PURE__ */ __name((obj) => {
589
+ if (!isObject(obj)) {
590
+ return false;
591
+ }
592
+ const tag = getObjectTag(obj);
593
+ return tag === "[object Error]" || tag === "[object DOMException]" || typeof obj?.message === "string" && typeof obj?.name === "string" && !isPlainObject(obj);
594
+ }, "isError");
595
+
596
+ // ../fs/src/read-file.ts
597
+ import { existsSync, readFileSync as readFileSyncFs } from "node:fs";
598
+ import { readFile as readFileFs } from "node:fs/promises";
599
+ var readFile = /* @__PURE__ */ __name(async (filePath) => {
600
+ try {
601
+ if (!filePath) {
602
+ throw new Error("No file path provided to read data");
603
+ }
604
+ return await readFileFs(filePath, {
605
+ encoding: "utf8"
606
+ });
607
+ } catch {
608
+ throw new Error("An error occurred writing data to file");
609
+ }
610
+ }, "readFile");
611
+ async function readJsonFile(path, options) {
612
+ const content = await readFile(path);
613
+ if (options) {
614
+ options.endsWithNewline = content.codePointAt(content.length - 1) === 10;
615
+ }
616
+ try {
617
+ return StormJSON.parseJson(content, options);
618
+ } catch (error) {
619
+ if (isError(error)) {
620
+ error.message = error.message.replace("JSON", path);
621
+ throw error;
622
+ }
623
+ throw new Error(`Failed to parse JSON: ${path}`);
624
+ }
625
+ }
626
+ __name(readJsonFile, "readJsonFile");
627
+
628
+ // ../path/src/file-path-fns.ts
629
+ import { relative } from "node:path";
630
+
631
+ // ../path/src/is-file.ts
632
+ import { lstatSync, statSync } from "node:fs";
633
+
634
+ // ../path/src/join-paths.ts
635
+ var _DRIVE_LETTER_START_RE = /^[A-Z]:\//i;
636
+ function normalizeWindowsPath(input = "") {
637
+ if (!input) {
638
+ return input;
639
+ }
640
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
641
+ }
642
+ __name(normalizeWindowsPath, "normalizeWindowsPath");
643
+ var _UNC_REGEX = /^[/\\]{2}/;
644
+ var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i;
645
+ var _DRIVE_LETTER_RE = /^[A-Z]:$/i;
646
+ var isAbsolute = /* @__PURE__ */ __name(function(p) {
647
+ return _IS_ABSOLUTE_RE.test(p);
648
+ }, "isAbsolute");
649
+ var correctPaths = /* @__PURE__ */ __name(function(path) {
650
+ if (!path || path.length === 0) {
651
+ return ".";
652
+ }
653
+ path = normalizeWindowsPath(path);
654
+ const isUNCPath = path.match(_UNC_REGEX);
655
+ const isPathAbsolute = isAbsolute(path);
656
+ const trailingSeparator = path[path.length - 1] === "/";
657
+ path = normalizeString(path, !isPathAbsolute);
658
+ if (path.length === 0) {
659
+ if (isPathAbsolute) {
660
+ return "/";
661
+ }
662
+ return trailingSeparator ? "./" : ".";
663
+ }
664
+ if (trailingSeparator) {
665
+ path += "/";
666
+ }
667
+ if (_DRIVE_LETTER_RE.test(path)) {
668
+ path += "/";
669
+ }
670
+ if (isUNCPath) {
671
+ if (!isPathAbsolute) {
672
+ return `//./${path}`;
673
+ }
674
+ return `//${path}`;
675
+ }
676
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
677
+ }, "correctPaths");
678
+ var joinPaths = /* @__PURE__ */ __name(function(...segments) {
679
+ let path = "";
680
+ for (const seg of segments) {
681
+ if (!seg) {
682
+ continue;
683
+ }
684
+ if (path.length > 0) {
685
+ const pathTrailing = path[path.length - 1] === "/";
686
+ const segLeading = seg[0] === "/";
687
+ const both = pathTrailing && segLeading;
688
+ if (both) {
689
+ path += seg.slice(1);
690
+ } else {
691
+ path += pathTrailing || segLeading ? seg : `/${seg}`;
692
+ }
693
+ } else {
694
+ path += seg;
695
+ }
696
+ }
697
+ return correctPaths(path);
698
+ }, "joinPaths");
699
+ function normalizeString(path, allowAboveRoot) {
700
+ let res = "";
701
+ let lastSegmentLength = 0;
702
+ let lastSlash = -1;
703
+ let dots = 0;
704
+ let char = null;
705
+ for (let index = 0; index <= path.length; ++index) {
706
+ if (index < path.length) {
707
+ char = path[index];
708
+ } else if (char === "/") {
709
+ break;
710
+ } else {
711
+ char = "/";
712
+ }
713
+ if (char === "/") {
714
+ if (lastSlash === index - 1 || dots === 1) {
715
+ } else if (dots === 2) {
716
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
717
+ if (res.length > 2) {
718
+ const lastSlashIndex = res.lastIndexOf("/");
719
+ if (lastSlashIndex === -1) {
720
+ res = "";
721
+ lastSegmentLength = 0;
722
+ } else {
723
+ res = res.slice(0, lastSlashIndex);
724
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
725
+ }
726
+ lastSlash = index;
727
+ dots = 0;
728
+ continue;
729
+ } else if (res.length > 0) {
730
+ res = "";
731
+ lastSegmentLength = 0;
732
+ lastSlash = index;
733
+ dots = 0;
734
+ continue;
735
+ }
736
+ }
737
+ if (allowAboveRoot) {
738
+ res += res.length > 0 ? "/.." : "..";
739
+ lastSegmentLength = 2;
740
+ }
741
+ } else {
742
+ if (res.length > 0) {
743
+ res += `/${path.slice(lastSlash + 1, index)}`;
744
+ } else {
745
+ res = path.slice(lastSlash + 1, index);
746
+ }
747
+ lastSegmentLength = index - lastSlash - 1;
748
+ }
749
+ lastSlash = index;
750
+ dots = 0;
751
+ } else if (char === "." && dots !== -1) {
752
+ ++dots;
753
+ } else {
754
+ dots = -1;
755
+ }
756
+ }
757
+ return res;
758
+ }
759
+ __name(normalizeString, "normalizeString");
760
+
761
+ // ../path/src/regex.ts
762
+ var DRIVE_LETTER_START_REGEX = /^[A-Z]:\//i;
763
+ var DRIVE_LETTER_REGEX = /^[A-Z]:$/i;
764
+ var UNC_REGEX = /^[/\\]{2}/;
765
+ var ABSOLUTE_PATH_REGEX = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^~[/\\]|^[A-Z]:[/\\]/i;
766
+
767
+ // ../path/src/slash.ts
768
+ function slash(path) {
769
+ if (path.startsWith("\\\\?\\")) {
770
+ return path;
771
+ }
772
+ return path.replace(/\\/g, "/");
773
+ }
774
+ __name(slash, "slash");
775
+
776
+ // ../path/src/is-file.ts
777
+ function isAbsolutePath(path) {
778
+ return ABSOLUTE_PATH_REGEX.test(slash(path));
779
+ }
780
+ __name(isAbsolutePath, "isAbsolutePath");
781
+
782
+ // ../path/src/correct-path.ts
783
+ function normalizeWindowsPath2(input = "") {
784
+ if (!input) {
785
+ return input;
786
+ }
787
+ return slash(input).replace(DRIVE_LETTER_START_REGEX, (r) => r.toUpperCase());
788
+ }
789
+ __name(normalizeWindowsPath2, "normalizeWindowsPath");
790
+ function correctPath(path) {
791
+ if (!path || path.length === 0) {
792
+ return ".";
793
+ }
794
+ path = normalizeWindowsPath2(path);
795
+ const isUNCPath = path.match(UNC_REGEX);
796
+ const isPathAbsolute = isAbsolutePath(path);
797
+ const trailingSeparator = path.endsWith("/");
798
+ path = normalizeString2(path, !isPathAbsolute);
799
+ if (path.length === 0) {
800
+ if (isPathAbsolute) {
801
+ return "/";
802
+ }
803
+ return trailingSeparator ? "./" : ".";
804
+ }
805
+ if (trailingSeparator) {
806
+ path += "/";
807
+ }
808
+ if (DRIVE_LETTER_REGEX.test(path)) {
809
+ path += "/";
810
+ }
811
+ if (isUNCPath) {
812
+ if (!isPathAbsolute) {
813
+ return `//./${path}`;
814
+ }
815
+ return `//${path}`;
816
+ }
817
+ return !path.startsWith("/") && isPathAbsolute && !DRIVE_LETTER_REGEX.test(path) ? `/${path}` : path;
818
+ }
819
+ __name(correctPath, "correctPath");
820
+ function normalizeString2(path, allowAboveRoot) {
821
+ let res = "";
822
+ let lastSegmentLength = 0;
823
+ let lastSlash = -1;
824
+ let dots = 0;
825
+ let char = null;
826
+ for (let index = 0; index <= path.length; ++index) {
827
+ if (index < path.length) {
828
+ char = path[index];
829
+ } else if (char === "/") {
830
+ break;
831
+ } else {
832
+ char = "/";
833
+ }
834
+ if (char === "/") {
835
+ if (lastSlash === index - 1 || dots === 1) {
836
+ } else if (dots === 2) {
837
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
838
+ if (res.length > 2) {
839
+ const lastSlashIndex = res.lastIndexOf("/");
840
+ if (lastSlashIndex === -1) {
841
+ res = "";
842
+ lastSegmentLength = 0;
843
+ } else {
844
+ res = res.slice(0, lastSlashIndex);
845
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
846
+ }
847
+ lastSlash = index;
848
+ dots = 0;
849
+ continue;
850
+ } else if (res.length > 0) {
851
+ res = "";
852
+ lastSegmentLength = 0;
853
+ lastSlash = index;
854
+ dots = 0;
855
+ continue;
856
+ }
857
+ }
858
+ if (allowAboveRoot) {
859
+ res += res.length > 0 ? "/.." : "..";
860
+ lastSegmentLength = 2;
861
+ }
862
+ } else {
863
+ if (res.length > 0) {
864
+ res += `/${path.slice(lastSlash + 1, index)}`;
865
+ } else {
866
+ res = path.slice(lastSlash + 1, index);
867
+ }
868
+ lastSegmentLength = index - lastSlash - 1;
869
+ }
870
+ lastSlash = index;
871
+ dots = 0;
872
+ } else if (char === "." && dots !== -1) {
873
+ ++dots;
874
+ } else {
875
+ dots = -1;
876
+ }
877
+ }
878
+ return res;
879
+ }
880
+ __name(normalizeString2, "normalizeString");
881
+
882
+ // ../path/src/get-workspace-root.ts
883
+ import { findWorkspaceRootSafe } from "@storm-software/config-tools";
884
+
885
+ // ../path/src/file-path-fns.ts
886
+ function findFileName(filePath, options = {}) {
887
+ const { requireExtension = false, withExtension = true } = options;
888
+ const result = normalizeWindowsPath2(filePath)?.split(filePath?.includes("\\") ? "\\" : "/")?.pop() ?? "";
889
+ if (requireExtension === true && !result.includes(".")) {
890
+ return EMPTY_STRING;
891
+ }
892
+ if (withExtension === false && result.includes(".")) {
893
+ return result.substring(0, result.lastIndexOf(".")) || EMPTY_STRING;
894
+ }
895
+ return result;
896
+ }
897
+ __name(findFileName, "findFileName");
898
+ function findFilePath(filePath) {
899
+ const normalizedPath = normalizeWindowsPath2(filePath);
900
+ const result = normalizedPath.replace(findFileName(normalizedPath, {
901
+ requireExtension: true
902
+ }), "");
903
+ return result === "/" ? result : result.replace(/\/$/, "");
904
+ }
905
+ __name(findFilePath, "findFilePath");
906
+
907
+ // bin/capnpc.ts
908
+ import { Command, Option } from "commander";
909
+ import ts from "typescript";
910
+
911
+ // ../path/src/exists.ts
912
+ import { existsSync as existsSyncFs } from "node:fs";
913
+ import { access, constants } from "node:fs/promises";
914
+ var existsSync2 = /* @__PURE__ */ __name((filePath) => {
915
+ return existsSyncFs(filePath);
916
+ }, "existsSync");
917
+ var exists = /* @__PURE__ */ __name(async (filePath) => {
918
+ return access(filePath, constants.F_OK).then(() => true).catch(() => false);
919
+ }, "exists");
920
+
921
+ // ../fs/src/helpers.ts
922
+ import { parseTar, parseTarGzip } from "nanotar";
923
+ import { createWriteStream, mkdirSync, rmSync } from "node:fs";
924
+ import { mkdir, readFile as readFile2, rm } from "node:fs/promises";
925
+ async function createDirectory(path) {
926
+ if (await exists(path)) {
927
+ return;
928
+ }
929
+ return mkdir(path, {
930
+ recursive: true
931
+ });
932
+ }
933
+ __name(createDirectory, "createDirectory");
934
+
935
+ // ../fs/src/write-file.ts
936
+ import { stringify as stringifyToml } from "@ltd/j-toml";
937
+ import defu2 from "defu";
938
+ import { writeFileSync as writeFileSyncFs } from "node:fs";
939
+ import { writeFile as writeFileFs } from "node:fs/promises";
940
+ var writeFile = /* @__PURE__ */ __name(async (filePath, content = "", options = {}) => {
941
+ if (!filePath) {
942
+ throw new Error("No file path provided to read data");
943
+ }
944
+ const directory = findFilePath(correctPath(filePath));
945
+ if (!existsSync2(directory)) {
946
+ if (options.createDirectory !== false) {
947
+ await createDirectory(directory);
948
+ } else {
949
+ throw new Error(`Directory ${directory} does not exist`);
950
+ }
951
+ }
952
+ return writeFileFs(filePath, content || "", options);
953
+ }, "writeFile");
954
+
955
+ // src/compile.ts
956
+ import { compileAll } from "capnp-es/compiler";
957
+ import { Buffer as Buffer3 } from "node:buffer";
958
+ import { exec } from "node:child_process";
959
+ import { existsSync as existsSync3 } from "node:fs";
960
+ async function readStdin() {
961
+ if (process.stdin.isTTY) {
962
+ return Buffer3.alloc(0);
963
+ }
964
+ const chunks = [];
965
+ process.stdin.on("data", (chunk) => {
966
+ chunks.push(chunk);
967
+ });
968
+ await new Promise((resolve) => {
969
+ process.stdin.on("end", resolve);
970
+ });
971
+ const reqBuffer = Buffer3.alloc(chunks.reduce((l, chunk) => l + chunk.byteLength, 0));
972
+ let i = 0;
973
+ for (const chunk of chunks) {
974
+ chunk.copy(reqBuffer, i);
975
+ i += chunk.byteLength;
976
+ }
977
+ return reqBuffer;
978
+ }
979
+ __name(readStdin, "readStdin");
980
+ async function capnpc(options) {
981
+ try {
982
+ const { outputPath, tsconfig, sourcePath = [] } = options;
983
+ let dataBuf = await readStdin();
984
+ if (dataBuf.byteLength === 0) {
985
+ const opts = [];
986
+ if (outputPath) {
987
+ opts.push(`-o-:${outputPath}`);
988
+ } else {
989
+ opts.push("-o-");
990
+ }
991
+ dataBuf = await new Promise((resolve) => {
992
+ exec(`capnpc ${opts.join(" ")} ${sourcePath.join(" ")}`, {
993
+ encoding: "buffer"
994
+ }, (error, stdout, stderr) => {
995
+ if (stderr.length > 0) {
996
+ process.stderr.write(stderr);
997
+ }
998
+ if (error) {
999
+ throw error;
1000
+ }
1001
+ resolve(stdout);
1002
+ });
1003
+ });
1004
+ }
1005
+ const result = await compileAll(dataBuf, {
1006
+ ts: options.ts ?? true,
1007
+ js: options.js ?? false,
1008
+ dts: options.dts ?? true,
1009
+ tsconfig: tsconfig?.options
1010
+ });
1011
+ for (const [fileName, content] of result.files) {
1012
+ let filePath = fileName;
1013
+ if (!existsSync3(findFilePath(filePath))) {
1014
+ const fullPath = `/${filePath}`;
1015
+ if (existsSync3(findFilePath(fullPath))) {
1016
+ filePath = fullPath;
1017
+ }
1018
+ }
1019
+ if (outputPath) {
1020
+ filePath = joinPaths(outputPath, fileName);
1021
+ }
1022
+ if (!existsSync3(findFilePath(filePath))) {
1023
+ await createDirectory(findFilePath(filePath));
1024
+ }
1025
+ await writeFile(
1026
+ filePath,
1027
+ // https://github.com/microsoft/TypeScript/issues/54632
1028
+ content.replace(/^\s+/gm, (match) => " ".repeat(match.length / 2))
1029
+ );
1030
+ }
1031
+ return result;
1032
+ } catch (error) {
1033
+ if (error instanceof Error) {
1034
+ console.error(`Error: ${error.message}`);
1035
+ if (error.stack) {
1036
+ console.error(error.stack);
1037
+ }
1038
+ } else {
1039
+ console.error("An unknown error occurred:", error);
1040
+ }
1041
+ throw error;
1042
+ }
1043
+ }
1044
+ __name(capnpc, "capnpc");
1045
+
1046
+ // bin/capnpc.ts
1047
+ function createProgram() {
1048
+ writeInfo("\u26A1 Running Storm Cap'n Proto Compiler Tools", {
1049
+ logLevel: "all"
1050
+ });
1051
+ const root = findWorkspaceRootSafe2(process.cwd());
1052
+ process.env.STORM_WORKSPACE_ROOT ??= root;
1053
+ process.env.NX_WORKSPACE_ROOT_PATH ??= root;
1054
+ if (root) {
1055
+ process.chdir(root);
1056
+ }
1057
+ const program = new Command("storm-capnpc");
1058
+ program.version("1.0.0", "-v --version", "display CLI version");
1059
+ const tsOption = new Option("--ts", "An indicator to generate TypeScript files").default(true);
1060
+ const jsOption = new Option("--js", "An indicator to generate JavaScript files").default(false);
1061
+ const dtsOption = new Option("--dts", "An indicator to generate TypeScript declaration files").default(true);
1062
+ const importPathOption = new Option("-I --import-path <dir...>", "Add <dir> to the list of directories searched for non-relative imports").default([]).argParser((val) => {
1063
+ if (val.startsWith("-I") || val.startsWith("--import-path")) {
1064
+ return val.split(",").map((dir) => dir.trim());
1065
+ }
1066
+ return [
1067
+ val.trim()
1068
+ ];
1069
+ });
1070
+ const generateId = new Option("-i --generate-id", "Generate a new 64-bit unique ID for use in a Cap'n Proto schema").default(true);
1071
+ const standardImportOption = new Option("--standard-import", "Add default import paths; use only those specified by -I").default(true);
1072
+ const outputPathOption = new Option("-o --output-path <path>", "The directory to output the generated files to").default(process.cwd());
1073
+ const sourceOption = new Option("--source-path <path...>", "The directories containing the Cap'n Proto schema files to compile (default: current working directory)").default([
1074
+ joinPaths(process.cwd(), "**/*.capnp")
1075
+ ]).argParser((val) => {
1076
+ if (val.startsWith("--source") || val.startsWith("-s")) {
1077
+ return val.split(",").map((dir) => dir.trim());
1078
+ }
1079
+ return [
1080
+ val.trim()
1081
+ ];
1082
+ });
1083
+ const tsconfigPathOption = new Option("--tsconfig-path <path>", "The path to the TypeScript configuration file to use for compilation").default(joinPaths(process.cwd(), "tsconfig.json"));
1084
+ program.command("compile", {
1085
+ isDefault: true
1086
+ }).description("Run the Storm Cap'n Proto compiler").addOption(sourceOption).addOption(outputPathOption).addOption(importPathOption).addOption(tsconfigPathOption).addOption(generateId).addOption(standardImportOption).addOption(tsOption).addOption(jsOption).addOption(dtsOption).action(compileAction).showSuggestionAfterError(true).showHelpAfterError(true);
1087
+ return program;
1088
+ }
1089
+ __name(createProgram, "createProgram");
1090
+ async function compileAction(options) {
1091
+ writeInfo(`\u{1F4E6} Storm Cap'n Proto Compiler will output ${options.ts ? "TypeScript code" : ""}${options.js ? options.ts ? ", JavaScript code" : "JavaScript code" : ""}${options.dts ? options.ts || options.js ? ", TypeScript declarations" : "TypeScript declarations" : ""} files to ${options.outputPath}...`, {
1092
+ logLevel: "all"
1093
+ });
1094
+ const resolvedTsconfig = await readJsonFile(options.tsconfigPath);
1095
+ const tsconfig = ts.parseJsonConfigFileContent(resolvedTsconfig, ts.sys, findFilePath(options.tsconfigPath));
1096
+ const sourcefiles = [];
1097
+ for (const sourcePath of options.sourcePath) {
1098
+ if (!sourcePath) {
1099
+ writeFatal(`\u274C The source path "${sourcePath}" is invalid. Please provide a valid path.`, {
1100
+ logLevel: "all"
1101
+ });
1102
+ return;
1103
+ }
1104
+ sourcefiles.push(...await listFiles(sourcePath));
1105
+ }
1106
+ if (sourcefiles.length === 0) {
1107
+ writeFatal(`\u274C No Cap'n Proto schema files found in the specified source paths: ${options.sourcePath.join(", ")}. Please ensure that the paths are correct and contain .capnp files.`, {
1108
+ logLevel: "all"
1109
+ });
1110
+ return;
1111
+ }
1112
+ const result = await capnpc({
1113
+ ...options,
1114
+ tsconfig,
1115
+ sourcePath: sourcefiles
1116
+ });
1117
+ if (result.files.size === 0) {
1118
+ writeInfo("\u26A0\uFE0F No files were generated. Please check your schema files.", {
1119
+ logLevel: "all"
1120
+ });
1121
+ return;
1122
+ }
1123
+ writeSuccess("\u26A1 Storm Cap'n Proto Compiler completed successfully.", {
1124
+ logLevel: "all"
1125
+ });
1126
+ }
1127
+ __name(compileAction, "compileAction");
1128
+ void (async () => {
1129
+ try {
1130
+ handleProcess();
1131
+ const program = createProgram();
1132
+ await program.parseAsync(process.argv);
1133
+ exitWithSuccess();
1134
+ } catch (error) {
1135
+ writeFatal(`A fatal error occurred while running the Storm Cap'n Proto compiler tool:
1136
+ ${error?.message ? error.message : JSON.stringify(error)}${error?.stack ? `
1137
+ Stack Trace: ${error.stack}` : ""}`, {
1138
+ logLevel: "all"
1139
+ });
1140
+ exitWithError();
1141
+ process.exit(1);
1142
+ }
1143
+ })();
1144
+ export {
1145
+ createProgram
1146
+ };