@r_masseater/masseater-utils 0.6.0 → 0.7.1

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 (160) hide show
  1. package/README.md +40 -36
  2. package/dist/browser-test/vite.d.mts +6 -0
  3. package/dist/browser-test/vite.mjs +29 -0
  4. package/dist/browser-test/vite.mjs.map +1 -0
  5. package/dist/button-variants-BLMlMm-s.mjs +31 -0
  6. package/dist/button-variants-BLMlMm-s.mjs.map +1 -0
  7. package/dist/button-variants-Bupz7GI3.d.mts +6 -0
  8. package/dist/cn-DtxpfSUK.mjs +7 -0
  9. package/dist/cn-DtxpfSUK.mjs.map +1 -0
  10. package/dist/effect2cs.d.mts +27 -0
  11. package/dist/effect2cs.mjs +75 -0
  12. package/dist/effect2cs.mjs.map +1 -0
  13. package/dist/effect2rs.d.mts +52 -0
  14. package/dist/effect2rs.mjs +870 -0
  15. package/dist/effect2rs.mjs.map +1 -0
  16. package/dist/github-workflow.d.mts +3 -33
  17. package/dist/github-workflow.mjs +2 -46
  18. package/dist/github-workflow.mjs.map +1 -1
  19. package/dist/headers-BK-aW9Kw.d.mts +81 -0
  20. package/dist/headers-Cr6gAurg.mjs +115 -0
  21. package/dist/headers-Cr6gAurg.mjs.map +1 -0
  22. package/dist/heading-class-CDq0WZpR.d.mts +10 -0
  23. package/dist/heading-class-H4Z13Bpn.mjs +14 -0
  24. package/dist/heading-class-H4Z13Bpn.mjs.map +1 -0
  25. package/dist/index-BkZOsFv4.d.mts +139 -0
  26. package/dist/index-CLb1-l_c.d.mts +28 -0
  27. package/dist/index-ChbPLmqu.d.mts +33 -0
  28. package/dist/lapse/sdk.d.mts +4 -0
  29. package/dist/lapse/sdk.mjs +11 -0
  30. package/dist/lapse/sdk.mjs.map +1 -0
  31. package/dist/lapse.d.mts +8 -0
  32. package/dist/lapse.mjs +43 -0
  33. package/dist/lapse.mjs.map +1 -0
  34. package/dist/local-server/node.d.mts +21 -0
  35. package/dist/local-server/node.mjs +81 -0
  36. package/dist/local-server/node.mjs.map +1 -0
  37. package/dist/local-server/serve.d.mts +9 -0
  38. package/dist/local-server/serve.mjs +13 -0
  39. package/dist/local-server/serve.mjs.map +1 -0
  40. package/dist/local-server.d.mts +19 -0
  41. package/dist/local-server.mjs +36 -0
  42. package/dist/local-server.mjs.map +1 -0
  43. package/dist/portfolio-BQJtJtfK.mjs +45 -0
  44. package/dist/portfolio-BQJtJtfK.mjs.map +1 -0
  45. package/dist/process-_W_7DeKe.d.mts +34 -0
  46. package/dist/process-lKS6nYWh.mjs +49 -0
  47. package/dist/process-lKS6nYWh.mjs.map +1 -0
  48. package/dist/process.d.mts +2 -0
  49. package/dist/process.mjs +1 -0
  50. package/dist/security-headers/http.d.mts +10 -0
  51. package/dist/security-headers/http.mjs +25 -0
  52. package/dist/security-headers/http.mjs.map +1 -0
  53. package/dist/security-headers/request.d.mts +3 -0
  54. package/dist/security-headers/request.mjs +15 -0
  55. package/dist/security-headers/request.mjs.map +1 -0
  56. package/dist/security-headers/response.d.mts +2 -0
  57. package/dist/security-headers/response.mjs +17 -0
  58. package/dist/security-headers/response.mjs.map +1 -0
  59. package/dist/security-headers/static.d.mts +2 -0
  60. package/dist/security-headers/static.mjs +1 -0
  61. package/dist/security-headers/vite.d.mts +2 -0
  62. package/dist/security-headers/vite.mjs +1 -0
  63. package/dist/security-headers.d.mts +3 -0
  64. package/dist/security-headers.mjs +3 -0
  65. package/dist/socket-port-CTg-qfiP.mjs +20 -0
  66. package/dist/socket-port-CTg-qfiP.mjs.map +1 -0
  67. package/dist/static-page-headers-_B0WGkew.mjs +133 -0
  68. package/dist/static-page-headers-_B0WGkew.mjs.map +1 -0
  69. package/dist/sync-BkyZGGDA.mjs +121 -0
  70. package/dist/sync-BkyZGGDA.mjs.map +1 -0
  71. package/dist/table-class-BeiCXlFj.d.mts +14 -0
  72. package/dist/table-class-RQvT6MYy.mjs +21 -0
  73. package/dist/table-class-RQvT6MYy.mjs.map +1 -0
  74. package/dist/ui/backdrop-palette.d.mts +10 -0
  75. package/dist/ui/backdrop-palette.mjs +13 -0
  76. package/dist/ui/backdrop-palette.mjs.map +1 -0
  77. package/dist/ui/badge.d.mts +12 -0
  78. package/dist/ui/badge.mjs +18 -0
  79. package/dist/ui/badge.mjs.map +1 -0
  80. package/dist/ui/browser-runtime.d.mts +3 -0
  81. package/dist/ui/browser-runtime.mjs +18 -0
  82. package/dist/ui/browser-runtime.mjs.map +1 -0
  83. package/dist/ui/button-variants.d.mts +2 -0
  84. package/dist/ui/button-variants.mjs +1 -0
  85. package/dist/ui/button.d.mts +7 -0
  86. package/dist/ui/button.mjs +30 -0
  87. package/dist/ui/button.mjs.map +1 -0
  88. package/dist/ui/cn.d.mts +3 -0
  89. package/dist/ui/cn.mjs +1 -0
  90. package/dist/ui/color-scheme.d.mts +2 -0
  91. package/dist/ui/color-scheme.mjs +13 -0
  92. package/dist/ui/color-scheme.mjs.map +1 -0
  93. package/dist/ui/heading-class.d.mts +2 -0
  94. package/dist/ui/heading-class.mjs +1 -0
  95. package/dist/ui/heading.d.mts +8 -0
  96. package/dist/ui/heading.mjs +34 -0
  97. package/dist/ui/heading.mjs.map +1 -0
  98. package/dist/ui/input-class.d.mts +2 -0
  99. package/dist/ui/input-class.mjs +5 -0
  100. package/dist/ui/input-class.mjs.map +1 -0
  101. package/dist/ui/native-select-class.d.mts +2 -0
  102. package/dist/ui/native-select-class.mjs +5 -0
  103. package/dist/ui/native-select-class.mjs.map +1 -0
  104. package/dist/ui/next-page-trigger.d.mts +5 -0
  105. package/dist/ui/next-page-trigger.mjs +29 -0
  106. package/dist/ui/next-page-trigger.mjs.map +1 -0
  107. package/dist/ui/page-footer.d.mts +10 -0
  108. package/dist/ui/page-footer.mjs +24 -0
  109. package/dist/ui/page-footer.mjs.map +1 -0
  110. package/dist/ui/page-header.d.mts +11 -0
  111. package/dist/ui/page-header.mjs +22 -0
  112. package/dist/ui/page-header.mjs.map +1 -0
  113. package/dist/ui/pointer.d.mts +14 -0
  114. package/dist/ui/pointer.mjs +51 -0
  115. package/dist/ui/pointer.mjs.map +1 -0
  116. package/dist/ui/portfolio.d.mts +31 -0
  117. package/dist/ui/portfolio.mjs +1 -0
  118. package/dist/ui/table-class.d.mts +2 -0
  119. package/dist/ui/table-class.mjs +1 -0
  120. package/dist/ui/table.d.mts +30 -0
  121. package/dist/ui/table.mjs +64 -0
  122. package/dist/ui/table.mjs.map +1 -0
  123. package/dist/ui/to-wavy-letters.d.mts +12 -0
  124. package/dist/ui/to-wavy-letters.mjs +9 -0
  125. package/dist/ui/to-wavy-letters.mjs.map +1 -0
  126. package/dist/ui/web-analytics.d.mts +18 -0
  127. package/dist/ui/web-analytics.mjs +19 -0
  128. package/dist/ui/web-analytics.mjs.map +1 -0
  129. package/dist/web-analytics-BM9LdncT.d.mts +4 -0
  130. package/dist/web-analytics-Bz6nyJmQ.mjs +6 -0
  131. package/dist/web-analytics-Bz6nyJmQ.mjs.map +1 -0
  132. package/dist/yohaku-protocol/sync.d.mts +2 -0
  133. package/dist/yohaku-protocol/sync.mjs +1 -0
  134. package/dist/yohaku-protocol.d.mts +2 -0
  135. package/dist/yohaku-protocol.mjs +1 -0
  136. package/package.json +131 -4
  137. package/skills/share-types-with-rust/SKILL.md +90 -0
  138. package/src/app/browser-test-fonts.conf +28 -0
  139. package/src/app/ui-styles.css +185 -0
  140. package/src/app/ui-theme.css +81 -0
  141. package/src/app/ui-view-transition.css +5 -0
  142. package/src/shared/lib/button-variants.ts +33 -0
  143. package/src/shared/lib/input-class.ts +2 -0
  144. package/src/shared/lib/native-select-class.ts +2 -0
  145. package/src/shared/lib/table-class.ts +35 -0
  146. package/src/shared/ui/badge.tsx +29 -0
  147. package/src/shared/ui/button.tsx +39 -0
  148. package/src/shared/ui/heading.tsx +38 -0
  149. package/src/shared/ui/next-page-trigger.tsx +34 -0
  150. package/src/shared/ui/page-footer.tsx +34 -0
  151. package/src/shared/ui/page-header.tsx +29 -0
  152. package/src/shared/ui/table/column-headings.tsx +30 -0
  153. package/src/shared/ui/table/index.ts +10 -0
  154. package/src/shared/ui/table/table-body.tsx +8 -0
  155. package/src/shared/ui/table/table-caption.tsx +8 -0
  156. package/src/shared/ui/table/table-cell.tsx +8 -0
  157. package/src/shared/ui/table/table-head.tsx +13 -0
  158. package/src/shared/ui/table/table-header.tsx +8 -0
  159. package/src/shared/ui/table/table-row.tsx +8 -0
  160. package/src/shared/ui/table/table.tsx +31 -0
@@ -0,0 +1,870 @@
1
+ import { Array, Boolean, Effect, FileSystem, Match, Option, Path, Predicate, Record, Schema, SchemaAST, SchemaRepresentation, String, pipe } from "effect";
2
+ // src/entities/rust-item/model/integer.ts
3
+ const IS_INT = "effect/schema/isInt";
4
+ const ZERO = 0;
5
+ const STEP = 1;
6
+ const U32_MAX = 4294967295;
7
+ const I32_MIN = -2147483648;
8
+ const I32_MAX = 2147483647;
9
+ const BoundsPayload = Schema.Struct({
10
+ minimum: Schema.optionalKey(Schema.Finite),
11
+ maximum: Schema.optionalKey(Schema.Finite),
12
+ exclusiveMinimum: Schema.optionalKey(Schema.Union([Schema.Finite, Schema.Boolean])),
13
+ exclusiveMaximum: Schema.optionalKey(Schema.Union([Schema.Finite, Schema.Boolean]))
14
+ });
15
+ const decodePayload = Schema.decodeUnknownOption(BoundsPayload);
16
+ const filters = (checks) => pipe(checks, Array.flatMap((check) => Match.value(check).pipe(Match.tagsExhaustive({
17
+ Filter: (filter) => [filter],
18
+ FilterGroup: (group) => filters(group.checks)
19
+ }))));
20
+ const shiftWhen = (step) => (flag) => Match.value(flag).pipe(Match.when(true, () => step), Match.orElse(() => ZERO));
21
+ const numbers = (values) => pipe(values, Array.filter(Predicate.isNumber));
22
+ const lows = (step) => (payload) => [...pipe(numbers([payload.minimum]), Array.map((minimum) => minimum + shiftWhen(step)(payload.exclusiveMinimum))), ...pipe(numbers([payload.exclusiveMinimum]), Array.map((minimum) => minimum + step))];
23
+ const highs = (step) => (payload) => [...pipe(numbers([payload.maximum]), Array.map((maximum) => maximum - shiftWhen(step)(payload.exclusiveMaximum))), ...pipe(numbers([payload.exclusiveMaximum]), Array.map((maximum) => maximum - step))];
24
+ const payloadOf = (filter) => pipe(Option.fromNullishOr(filter.representation), Option.flatMap(({ payload }) => decodePayload(payload)));
25
+ const isIntFilter = (filter) => pipe(Option.fromNullishOr(filter.representation), Option.exists(({ id }) => id === IS_INT));
26
+ const choose = (bounds) => Match.value(bounds).pipe(Match.when(({ int }) => !int, () => "f64"), Match.when(({ min, max }) => min >= ZERO && max <= U32_MAX, () => "u32"), Match.when(({ min }) => min >= ZERO, () => "u64"), Match.when(({ min, max }) => min >= I32_MIN && max <= I32_MAX, () => "i32"), Match.orElse(() => "i64"));
27
+ const numberType = (checks) => {
28
+ const flat = filters(checks);
29
+ const int = pipe(flat, Array.some(isIntFilter));
30
+ const step = Match.value(int).pipe(Match.when(true, () => STEP), Match.orElse(() => ZERO));
31
+ const payloads = pipe(flat, Array.map(payloadOf), Array.getSomes);
32
+ const minimums = pipe(payloads, Array.flatMap(lows(step)));
33
+ const maximums = pipe(payloads, Array.flatMap(highs(step)));
34
+ return choose({
35
+ int,
36
+ min: Math.max(Number.NEGATIVE_INFINITY, ...minimums),
37
+ max: Math.min(Number.POSITIVE_INFINITY, ...maximums)
38
+ });
39
+ };
40
+ // src/entities/rust-item/model/names.ts
41
+ const KEYWORDS = /* @__PURE__ */ new Set([
42
+ "as",
43
+ "async",
44
+ "await",
45
+ "box",
46
+ "break",
47
+ "const",
48
+ "continue",
49
+ "dyn",
50
+ "else",
51
+ "enum",
52
+ "extern",
53
+ "false",
54
+ "fn",
55
+ "for",
56
+ "gen",
57
+ "if",
58
+ "impl",
59
+ "in",
60
+ "let",
61
+ "loop",
62
+ "match",
63
+ "mod",
64
+ "move",
65
+ "mut",
66
+ "pub",
67
+ "ref",
68
+ "return",
69
+ "static",
70
+ "struct",
71
+ "trait",
72
+ "true",
73
+ "try",
74
+ "type",
75
+ "unsafe",
76
+ "use",
77
+ "where",
78
+ "while",
79
+ "yield"
80
+ ]);
81
+ const LOWER_TO_UPPER = /(?<before>[a-z0-9])(?<after>[A-Z])/gu;
82
+ const ACRONYM_END = /(?<acronym>[A-Z]+)(?<next>[A-Z][a-z])/gu;
83
+ const SEPARATOR = /[^A-Za-z0-9]+/u;
84
+ const LEADING_DIGIT = /^[0-9]/u;
85
+ const SCREAMING = /^[A-Z][A-Z0-9_]*$/u;
86
+ const INNER_UPPER = /(?<!^)(?<upper>[A-Z])/gu;
87
+ const RAW_PREFIX = /^r#/u;
88
+ const TRAILING_UNDERSCORES = /_+$/u;
89
+ const words = (value) => pipe(value, String.replaceAll(LOWER_TO_UPPER, "$<before> $<after>"), String.replaceAll(ACRONYM_END, "$<acronym> $<next>"), String.split(SEPARATOR), Array.filter(String.isNonEmpty));
90
+ const withLeadingDigit = (prefix) => (value) => Boolean.match(LEADING_DIGIT.test(value), {
91
+ onTrue: () => `${prefix}${value}`,
92
+ onFalse: () => value
93
+ });
94
+ const capitalized = (word) => pipe(word, String.toLowerCase, String.capitalize);
95
+ const snakeCase = (value) => pipe(words(value), Array.map(String.toLowerCase), Array.join("_"), withLeadingDigit("field_"));
96
+ const pascalCase = (value) => pipe(words(value), Array.map(capitalized), Array.join(""), withLeadingDigit("V"));
97
+ const screamingSnakeCase = (value) => Boolean.match(SCREAMING.test(value), {
98
+ onTrue: () => value,
99
+ onFalse: () => pipe(value, snakeCase, String.toUpperCase)
100
+ });
101
+ const plainIdentifier = (identifier) => pipe(identifier, String.replace(RAW_PREFIX, ""));
102
+ const UNRAWABLE = /* @__PURE__ */ new Set([
103
+ "self",
104
+ "super",
105
+ "crate",
106
+ "Self"
107
+ ]);
108
+ const FIRST_SUFFIX = 2;
109
+ const NEXT = 1;
110
+ const orFallback = (fallback) => (value) => Boolean.match(String.isNonEmpty(value), {
111
+ onTrue: () => value,
112
+ onFalse: () => fallback
113
+ });
114
+ const awayFromKeywords = (suffix) => (value) => Boolean.match(UNRAWABLE.has(value), {
115
+ onTrue: () => `${value}${suffix}`,
116
+ onFalse: () => value
117
+ });
118
+ const fieldIdentifier = (snake) => {
119
+ const safe = pipe(snake, orFallback("value"), awayFromKeywords("_"));
120
+ return Boolean.match(KEYWORDS.has(safe), {
121
+ onTrue: () => `r#${safe}`,
122
+ onFalse: () => safe
123
+ });
124
+ };
125
+ const variantIdentifier = (value) => pipe(pascalCase(value), orFallback("Value"), awayFromKeywords("Value"));
126
+ const firstFree = (taken) => (separator) => (name) => (suffix) => {
127
+ const candidate = Boolean.match(suffix === 1, {
128
+ onTrue: () => name,
129
+ onFalse: () => `${pipe(name, String.replace(TRAILING_UNDERSCORES, ""))}${separator}${globalThis.String(suffix)}`
130
+ });
131
+ const used = pipe(taken, Array.contains(plainIdentifier(candidate)));
132
+ return Boolean.match(used, {
133
+ onTrue: () => firstFree(taken)(separator)(name)(Math.max(suffix + NEXT, FIRST_SUFFIX)),
134
+ onFalse: () => candidate
135
+ });
136
+ };
137
+ const distinctFrom = (separator) => (taken) => (names) => pipe(names, Array.match({
138
+ onEmpty: () => [],
139
+ onNonEmpty: ([name, ...rest]) => {
140
+ const chosen = firstFree(taken)(separator)(name)(1);
141
+ return [chosen, ...distinctFrom(separator)([...taken, plainIdentifier(chosen)])(rest)];
142
+ }
143
+ }));
144
+ const distinct = (separator) => distinctFrom(separator)([]);
145
+ const serdeCamelField = (field) => pipe(field, String.split("_"), Array.map(String.capitalize), Array.join(""), String.uncapitalize);
146
+ const snakeVariant = (separator) => (variant) => pipe(variant, String.replaceAll(INNER_UPPER, `${separator}$<upper>`), String.toLowerCase);
147
+ const VARIANT_RULES = [
148
+ ["lowercase", String.toLowerCase],
149
+ ["kebab-case", snakeVariant("-")],
150
+ ["snake_case", snakeVariant("_")],
151
+ ["camelCase", String.uncapitalize],
152
+ ["SCREAMING_SNAKE_CASE", (variant) => pipe(variant, snakeVariant("_"), String.toUpperCase)],
153
+ ["UPPERCASE", String.toUpperCase]
154
+ ];
155
+ const variantRule = (variants) => pipe(VARIANT_RULES, Array.findFirst(([, apply]) => pipe(variants, Array.every(({ variant, value }) => apply(variant) === value))), Option.map(([rule]) => rule));
156
+ // src/entities/rust-item/model/types.ts
157
+ const taggedError$2 = Schema.TaggedError;
158
+ var UnsupportedSchema = class extends taggedError$2()("UnsupportedSchema", {
159
+ path: Schema.String,
160
+ reason: Schema.String
161
+ }) {};
162
+ const prim = (name) => ({
163
+ _tag: "Prim",
164
+ name
165
+ });
166
+ const json = { _tag: "Json" };
167
+ const named = (name) => ({
168
+ _tag: "Named",
169
+ name
170
+ });
171
+ const optional = (of) => ({
172
+ _tag: "Optional",
173
+ of
174
+ });
175
+ const list = (of) => ({
176
+ _tag: "List",
177
+ of
178
+ });
179
+ const dictionary = ([key, value]) => ({
180
+ _tag: "Dictionary",
181
+ key,
182
+ value
183
+ });
184
+ const tuple = (items) => ({
185
+ _tag: "Tuple",
186
+ items
187
+ });
188
+ const boxed = (of) => ({
189
+ _tag: "Boxed",
190
+ of
191
+ });
192
+ // src/entities/rust-item/model/lower.ts
193
+ const SINGLE$1 = 1;
194
+ const refuse = (path) => (reason) => Effect.fail(UnsupportedSchema.make({
195
+ path,
196
+ reason
197
+ }));
198
+ const isNull = (representation) => Predicate.isTagged(representation, "Null");
199
+ const isUndefined = (representation) => Predicate.isTagged(representation, "Undefined") || Predicate.isTagged(representation, "Void");
200
+ const isAbsent = (representation) => isNull(representation) || isUndefined(representation);
201
+ const partsOf = (representation) => Match.value(representation).pipe(Match.tag("Union", ({ types }) => ({
202
+ members: pipe(types, Array.filter(Predicate.not(isAbsent))),
203
+ nullable: pipe(types, Array.some(isNull)),
204
+ undefinable: pipe(types, Array.some(isUndefined))
205
+ })), Match.orElse(() => ({
206
+ members: [representation],
207
+ nullable: false,
208
+ undefinable: false
209
+ })));
210
+ const wrapOptional = (ty) => Match.value(ty).pipe(Match.tag("Optional", () => ty), Match.orElse(() => optional(ty)));
211
+ const optionalWhen = (absent) => (ty) => Match.value(absent).pipe(Match.when(true, () => wrapOptional(ty)), Match.orElse(() => ty));
212
+ const literal = (path) => (value) => Match.value(value).pipe(Match.when(Predicate.isString, () => Effect.succeed(prim("String"))), Match.when(Predicate.isBoolean, () => Effect.succeed(prim("bool"))), Match.when(Number.isInteger, () => Effect.succeed(prim("i64"))), Match.when(Predicate.isNumber, () => Effect.succeed(prim("f64"))), Match.orElse(() => refuse(path)("bigint literals have no JSON form")));
213
+ const UNION_REASON = "only an identified union of string literals, or of structs sharing a literal tag, becomes a Rust enum";
214
+ const union = (path, lower) => (representation) => {
215
+ const { members, nullable, undefinable } = partsOf(representation);
216
+ return pipe(Option.liftPredicate(members, (all) => all.length === SINGLE$1), Option.flatMap(Array.head), Option.match({
217
+ onNone: () => refuse(path)(UNION_REASON),
218
+ onSome: (only) => pipe(lower(path)(only), Effect.map(optionalWhen(nullable || undefinable)))
219
+ }));
220
+ };
221
+ const objects = (path, lower) => (object) => pipe(Array.head(object.indexSignatures), Option.filter(() => Array.isReadonlyArrayEmpty(object.propertySignatures)), Option.match({
222
+ onNone: () => refuse(path)("a struct needs an identifier"),
223
+ onSome: ({ parameter, type }) => pipe(Effect.all([lower(`${path}[key]`)(parameter), lower(`${path}[]`)(type)], { concurrency: 1 }), Effect.map(dictionary))
224
+ }));
225
+ const isList = ({ elements, rest }) => Array.isReadonlyArrayEmpty(elements) && rest.length === SINGLE$1;
226
+ const isTuple = ({ elements, rest }) => Array.isReadonlyArrayEmpty(rest) && Array.isReadonlyArrayNonEmpty(elements);
227
+ const arrays = (path, lower) => (array) => Match.value(array).pipe(Match.when(isList, ({ rest }) => pipe(Array.head(rest), Option.match({
228
+ onNone: () => refuse(path)("an array needs an element type"),
229
+ onSome: (element) => pipe(lower(`${path}[]`)(element), Effect.map(list))
230
+ }))), Match.when(isTuple, ({ elements }) => pipe(elements, (items) => Effect.forEach(items, ({ type }, index) => lower(`${path}[${index}]`)(type), { concurrency: 1 }), Effect.map(tuple))), Match.orElse(() => refuse(path)("only arrays and fixed tuples are supported")));
231
+ const lower = (path) => (representation) => Match.value(representation).pipe(Match.tagsExhaustive({
232
+ Reference: ({ $ref }) => Effect.succeed(named($ref)),
233
+ String: () => Effect.succeed(prim("String")),
234
+ TemplateLiteral: () => Effect.succeed(prim("String")),
235
+ Boolean: () => Effect.succeed(prim("bool")),
236
+ Number: ({ checks }) => Effect.succeed(prim(numberType(checks))),
237
+ Unknown: () => Effect.succeed(json),
238
+ Any: () => Effect.succeed(json),
239
+ ObjectKeyword: () => Effect.succeed(json),
240
+ Literal: ({ literal: value }) => literal(path)(value),
241
+ Suspend: ({ thunk }) => pipe(lower(path)(thunk), Effect.map(boxed)),
242
+ Union: union(path, lower),
243
+ Objects: objects(path, lower),
244
+ Arrays: arrays(path, lower),
245
+ Enum: () => refuse(path)("an enum needs an identifier"),
246
+ Declaration: () => refuse(path)("a declaration has no wire form"),
247
+ Null: () => refuse(path)("null alone has no Rust type"),
248
+ Undefined: () => refuse(path)("undefined alone has no Rust type"),
249
+ Void: () => refuse(path)("void has no Rust type"),
250
+ Never: () => refuse(path)("never has no Rust type"),
251
+ BigInt: () => refuse(path)("bigint has no JSON form"),
252
+ Symbol: () => refuse(path)("symbol has no JSON form"),
253
+ UniqueSymbol: () => refuse(path)("symbol has no JSON form")
254
+ }));
255
+ const descriptionOf = (value) => pipe(Option.liftPredicate(value, Predicate.hasProperty("annotations")), Option.flatMapNullishOr(({ annotations }) => annotations), Option.filter(Predicate.hasProperty("description")), Option.map(({ description }) => description), Option.filter(Predicate.isString));
256
+ const fieldDescription = (signature) => pipe(descriptionOf(signature), Option.orElse(() => descriptionOf(signature.type)));
257
+ const keyedField = (path, signature) => (key) => {
258
+ const { nullable, undefinable } = partsOf(signature.type);
259
+ const absent = signature.isOptional || undefinable;
260
+ return pipe(lower(`${path}.${key}`)(signature.type), Effect.map((ty) => ({
261
+ rust: fieldIdentifier(snakeCase(key)),
262
+ key,
263
+ ty: optionalWhen(absent)(ty),
264
+ skipNone: absent && !nullable,
265
+ doc: fieldDescription(signature)
266
+ })));
267
+ };
268
+ const field = (path) => (signature) => pipe(Option.liftPredicate(signature.name, Predicate.isString), Option.match({
269
+ onNone: () => Effect.fail(UnsupportedSchema.make({
270
+ path,
271
+ reason: "only string keys can become Rust fields"
272
+ })),
273
+ onSome: keyedField(path, signature)
274
+ }));
275
+ // src/entities/rust-item/model/items.ts
276
+ const MIN_VARIANTS = 2;
277
+ const resolve = (references) => (representation) => Match.value(representation).pipe(Match.tag("Reference", ({ $ref }) => pipe(Option.fromNullishOr(references[$ref]), Option.getOrElse(() => representation))), Match.orElse(() => representation));
278
+ const stringLiteral = (representation) => Match.value(representation).pipe(Match.tag("Literal", ({ literal }) => Option.liftPredicate(literal, Predicate.isString)), Match.orElse(() => Option.none()));
279
+ const asObjects = (representation) => Match.value(representation).pipe(Match.tag("Objects", (objects) => Option.liftPredicate(objects, ({ indexSignatures }) => Array.isReadonlyArrayEmpty(indexSignatures))), Match.orElse(() => Option.none()));
280
+ const allSome = (options) => {
281
+ const values = Array.getSomes(options);
282
+ return Option.liftPredicate(values, (found) => found.length === options.length);
283
+ };
284
+ const tagValue = (key) => (objects) => pipe(objects.propertySignatures, Array.findFirst(({ name }) => name === key), Option.flatMap(({ type }) => stringLiteral(type)));
285
+ const distinctTags = (members) => (key) => {
286
+ const tags = pipe(members, Array.map(tagValue(key)));
287
+ return pipe(allSome(tags), Option.exists((values) => new Set(values).size === values.length));
288
+ };
289
+ const discriminator = (members) => pipe(Array.head(members), Option.filter(() => members.length >= MIN_VARIANTS), Option.flatMap(({ propertySignatures }) => pipe(propertySignatures, Array.map(({ name }) => name), Array.filter(Predicate.isString), Array.findFirst(distinctTags(members)))));
290
+ const withDistinctNames = (fields) => {
291
+ const names = pipe(fields, Array.map(({ rust }) => rust), distinct("_"));
292
+ return pipe(fields, Array.zipWith(names, (entry, rust) => ({
293
+ ...entry,
294
+ rust
295
+ })));
296
+ };
297
+ const fieldsOf = (path, skip) => (objects) => pipe(objects.propertySignatures, Array.filter(({ name }) => !Option.contains(skip, name)), (items) => Effect.forEach(items, field(path), { concurrency: 1 }), Effect.map(withDistinctNames));
298
+ const variantOf = (path, tag) => (member) => pipe(fieldsOf(path, Option.some(tag))(member), Effect.map((fields) => ({
299
+ value: pipe(tagValue(tag)(member), Option.getOrElse(() => tag)),
300
+ doc: descriptionOf(member),
301
+ fields
302
+ })));
303
+ const alias = ([name, representation]) => pipe(lower(name)(representation), Effect.map((ty) => ({
304
+ _tag: "Alias",
305
+ name,
306
+ doc: descriptionOf(representation),
307
+ ty
308
+ })));
309
+ const tagged$1 = ([name, representation]) => (members) => pipe(discriminator(members), Option.map((tag) => pipe(members, (items) => Effect.forEach(items, variantOf(name, tag), { concurrency: 1 }), Effect.map((variants) => ({
310
+ _tag: "Tagged",
311
+ name,
312
+ doc: descriptionOf(representation),
313
+ tag,
314
+ variants
315
+ })))));
316
+ const enumeration = ([name, representation]) => (values) => pipe(allSome(values), Option.filter(Array.isReadonlyArrayNonEmpty), Option.map((literals) => Effect.succeed({
317
+ _tag: "Enumeration",
318
+ name,
319
+ doc: descriptionOf(representation),
320
+ values: literals
321
+ })));
322
+ const unionItem = (references) => (entry) => {
323
+ const [, representation] = entry;
324
+ const { members, nullable, undefinable } = partsOf(representation);
325
+ const resolved = pipe(members, Array.map(resolve(references)));
326
+ const objects = allSome(pipe(resolved, Array.map(asObjects)));
327
+ const literals = pipe(members, Array.map(stringLiteral));
328
+ const asTagged = () => pipe(objects, Option.flatMap(tagged$1(entry)));
329
+ return pipe(Option.liftPredicate(members, () => !nullable && !undefinable), Option.flatMap(() => pipe(enumeration(entry)(literals), Option.orElse(asTagged))), Option.getOrElse(() => alias(entry)));
330
+ };
331
+ const enumItem = (entry) => ({ enums }) => {
332
+ const values = pipe(enums, Array.map(([, value]) => Option.liftPredicate(value, Predicate.isString)));
333
+ return pipe(enumeration(entry)(values), Option.getOrElse(() => alias(entry)));
334
+ };
335
+ const structItem = (entry) => {
336
+ const [name, representation] = entry;
337
+ return pipe(asObjects(representation), Option.match({
338
+ onNone: () => alias(entry),
339
+ onSome: (objects) => pipe(fieldsOf(name, Option.none())(objects), Effect.map((fields) => ({
340
+ _tag: "Struct",
341
+ name,
342
+ doc: descriptionOf(representation),
343
+ fields
344
+ })))
345
+ }));
346
+ };
347
+ const itemOf = (references) => (entry) => {
348
+ const [, representation] = entry;
349
+ return Match.value(representation).pipe(Match.tag("Union", () => unionItem(references)(entry)), Match.tag("Enum", enumItem(entry)), Match.orElse(() => structItem(entry)));
350
+ };
351
+ // src/features/check-rust/model/copies.ts
352
+ const DECLARATION = /^[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?(?:struct|enum|type|const(?![ \t]+(?:fn|unsafe|async|extern)\b)|static)[ \t]+(?<name>[A-Za-z_]\w*)/gmu;
353
+ const START = 0;
354
+ const declaredIn = (source) => pipe(Array.fromIterable(String.matchAll(DECLARATION)(source)), Array.flatMap((found) => pipe(Option.fromNullishOr(found.groups), Option.flatMap(({ name }) => Option.fromNullishOr(name)), Option.map((name) => ({
355
+ name,
356
+ index: found.index ?? START
357
+ })), Option.toArray)));
358
+ const lineAt = (source) => (index) => pipe(source, String.slice(START, index), String.split("\n"), Array.length);
359
+ const copiesIn = (generated) => ({ path, source }) => pipe(declaredIn(source), Array.filter(({ name }) => pipe(generated, Array.contains(name))), Array.map(({ name, index }) => ({
360
+ path,
361
+ line: lineAt(source)(index),
362
+ name
363
+ })));
364
+ const copiesOf = (generated) => (files) => {
365
+ const names = pipe(declaredIn(generated), Array.map(({ name }) => name));
366
+ return pipe(files, Array.flatMap(copiesIn(names)));
367
+ };
368
+ // src/features/check-rust/model/hand-written-copies.ts
369
+ const taggedError$1 = Schema.TaggedError;
370
+ const CopyLocation = Schema.Struct({
371
+ path: Schema.String,
372
+ line: Schema.Finite,
373
+ name: Schema.String
374
+ });
375
+ var HandWrittenCopies = class extends taggedError$1()("HandWrittenCopies", {
376
+ copies: Schema.Array(CopyLocation),
377
+ message: Schema.String
378
+ }) {};
379
+ const handWrittenCopies = (copies) => {
380
+ const places = pipe(copies, Array.map(({ path, line, name }) => `${path}:${line} declares ${name}`), Array.join("\n"));
381
+ return HandWrittenCopies.make({
382
+ copies,
383
+ message: `These Rust items are generated by effect2rs, so declare them only in the generated file and import them from there:\n${places}`
384
+ });
385
+ };
386
+ // src/features/check-rust/model/stale-rust.ts
387
+ const taggedError = Schema.TaggedError;
388
+ var StaleRust = class extends taggedError()("StaleRust", {
389
+ path: Schema.String,
390
+ message: Schema.String
391
+ }) {};
392
+ const staleRust = (path) => StaleRust.make({
393
+ path,
394
+ message: `${path} does not match the Effect Schema. Generate it again with effect2rs.`
395
+ });
396
+ // src/shared/lib/text.ts
397
+ const CONTROL_LIMIT = 32;
398
+ const HEX = 16;
399
+ const FIRST = 0;
400
+ const { raw } = globalThis.String;
401
+ const when = (condition) => (lines) => Boolean.match(condition, {
402
+ onTrue: lines,
403
+ onFalse: () => []
404
+ });
405
+ const docLines = (indent) => (doc) => pipe(doc, Option.map((text) => pipe(text, String.split("\n"), Array.map((line) => String.trimEnd(`${indent}/// ${line}`)))), Option.getOrElse(() => []));
406
+ const control = (char) => pipe(char, String.codePointAt(FIRST), Option.filter((point) => point < CONTROL_LIMIT));
407
+ const escapeChar = (char) => Match.value(char).pipe(Match.when("\\", () => raw`\\`), Match.when("\"", () => raw`\"`), Match.when("\n", () => raw`\n`), Match.when("\r", () => raw`\r`), Match.when(" ", () => raw`\t`), Match.orElse((value) => pipe(control(value), Option.match({
408
+ onNone: () => value,
409
+ onSome: (point) => `${raw`\u`}{${point.toString(HEX)}}`
410
+ }))));
411
+ const escape = (value) => pipe(Array.fromIterable(value), Array.map(escapeChar), Array.join(""));
412
+ const attribute = ({ name, parts, indent }) => when(Array.isReadonlyArrayNonEmpty(parts))(() => [`${indent}#[${name}(${pipe(parts, Array.join(", "))})]`]);
413
+ // src/features/render-rust/model/render-enum.ts
414
+ const variantsOf = (values) => {
415
+ const names = pipe(values, Array.map(variantIdentifier), distinct(""));
416
+ return pipe(values, Array.zipWith(names, (value, variant) => ({
417
+ variant,
418
+ value
419
+ })));
420
+ };
421
+ const ruleFor = (variants) => {
422
+ const identity = pipe(variants, Array.every(({ variant, value }) => variant === value));
423
+ return Boolean.match(identity, {
424
+ onTrue: () => Option.some(Option.none()),
425
+ onFalse: () => pipe(variantRule(variants), Option.map(Option.some))
426
+ });
427
+ };
428
+ const variantNaming = (variants) => {
429
+ const rule = ruleFor(variants);
430
+ return {
431
+ renameAll: pipe(rule, Option.flatten, Option.map((name) => `rename_all = "${name}"`), Option.toArray),
432
+ perVariant: (value) => Boolean.match(Option.isSome(rule), {
433
+ onTrue: () => [],
434
+ onFalse: () => [`rename = "${escape(value)}"`]
435
+ })
436
+ };
437
+ };
438
+ const ARM = " ";
439
+ const asStr = (variants) => [
440
+ " #[must_use]",
441
+ " pub const fn as_str(self) -> &'static str {",
442
+ " match self {",
443
+ ...pipe(variants, Array.map(({ variant, value }) => `${ARM}Self::${variant} => "${escape(value)}",`)),
444
+ " }",
445
+ " }"
446
+ ];
447
+ const parse = (variants) => [
448
+ " #[must_use]",
449
+ " pub fn parse(value: &str) -> Option<Self> {",
450
+ " match value {",
451
+ ...pipe(variants, Array.map(({ variant, value }) => `${ARM}"${escape(value)}" => Some(Self::${variant}),`)),
452
+ `${ARM}_ => None,`,
453
+ " }",
454
+ " }"
455
+ ];
456
+ const variantLines = (naming) => ({ variant, value }) => pipe(attribute({
457
+ name: "serde",
458
+ parts: naming.perVariant(value),
459
+ indent: " "
460
+ }), Array.append(` ${variant},`));
461
+ const enumLines = (derive) => ({ name, doc, values }) => {
462
+ const variants = variantsOf(values);
463
+ const naming = variantNaming(variants);
464
+ return [
465
+ ...docLines("")(doc),
466
+ derive,
467
+ ...attribute({
468
+ name: "serde",
469
+ parts: naming.renameAll,
470
+ indent: ""
471
+ }),
472
+ `pub enum ${name} {`,
473
+ ...pipe(variants, Array.flatMap(variantLines(naming))),
474
+ "}",
475
+ "",
476
+ `impl ${name} {`,
477
+ ...asStr(variants),
478
+ "",
479
+ ...parse(variants),
480
+ "}"
481
+ ];
482
+ };
483
+ // src/features/render-rust/model/rust-type.ts
484
+ const WIDE_INTEGERS = /* @__PURE__ */ new Set(["i64", "u64"]);
485
+ const SPECTA_NUMBER = "specta_typescript::Number";
486
+ const SPECTA_UNKNOWN = "specta_typescript::Unknown";
487
+ const SINGLE = 1;
488
+ const tupleType = (items) => Match.value(items.length).pipe(Match.when(SINGLE, () => `(${pipe(items, Array.join(""))},)`), Match.orElse(() => `(${pipe(items, Array.join(", "))})`));
489
+ const rustType = (ty) => Match.value(ty).pipe(Match.tagsExhaustive({
490
+ Prim: ({ name }) => name,
491
+ Json: () => "serde_json::Value",
492
+ Named: ({ name }) => name,
493
+ Optional: ({ of }) => `Option<${rustType(of)}>`,
494
+ List: ({ of }) => `Vec<${rustType(of)}>`,
495
+ Dictionary: ({ key, value }) => `BTreeMap<${rustType(key)}, ${rustType(value)}>`,
496
+ Tuple: ({ items }) => tupleType(pipe(items, Array.map(rustType))),
497
+ Boxed: ({ of }) => `Box<${rustType(of)}>`
498
+ }));
499
+ const spectaType = (aliasOf) => (ty) => Match.value(ty).pipe(Match.tagsExhaustive({
500
+ Prim: ({ name }) => Match.value(WIDE_INTEGERS.has(name)).pipe(Match.when(true, () => prim(SPECTA_NUMBER)), Match.orElse(() => ty)),
501
+ Json: () => prim(SPECTA_UNKNOWN),
502
+ Named: ({ name }) => pipe(aliasOf(name), Option.flatMap((target) => Option.liftPredicate(spectaType(aliasOf)(target), (override) => rustType(override) !== rustType(target))), Option.getOrElse(() => ty)),
503
+ Optional: (inner) => ({
504
+ ...inner,
505
+ of: spectaType(aliasOf)(inner.of)
506
+ }),
507
+ List: (inner) => ({
508
+ ...inner,
509
+ of: spectaType(aliasOf)(inner.of)
510
+ }),
511
+ Boxed: (inner) => ({
512
+ ...inner,
513
+ of: spectaType(aliasOf)(inner.of)
514
+ }),
515
+ Dictionary: (inner) => ({
516
+ ...inner,
517
+ key: spectaType(aliasOf)(inner.key),
518
+ value: spectaType(aliasOf)(inner.value)
519
+ }),
520
+ Tuple: (inner) => ({
521
+ ...inner,
522
+ items: pipe(inner.items, Array.map(spectaType(aliasOf)))
523
+ })
524
+ }));
525
+ const someTy = (predicate) => (ty) => predicate(ty) || Match.value(ty).pipe(Match.tagsExhaustive({
526
+ Prim: () => false,
527
+ Json: () => false,
528
+ Named: () => false,
529
+ Optional: ({ of }) => someTy(predicate)(of),
530
+ List: ({ of }) => someTy(predicate)(of),
531
+ Boxed: ({ of }) => someTy(predicate)(of),
532
+ Dictionary: ({ key, value }) => someTy(predicate)(key) || someTy(predicate)(value),
533
+ Tuple: ({ items }) => pipe(items, Array.some(someTy(predicate)))
534
+ }));
535
+ // src/features/render-rust/model/render-fields.ts
536
+ const camelCased = (fields) => pipe(fields, Array.some(({ rust, key }) => plainIdentifier(rust) !== key));
537
+ const serdeParts = (camel) => (field) => {
538
+ const plain = plainIdentifier(field.rust);
539
+ const expected = Boolean.match(camel, {
540
+ onTrue: () => serdeCamelField(plain),
541
+ onFalse: () => plain
542
+ });
543
+ return [...when(expected !== field.key)(() => [`rename = "${escape(field.key)}"`]), ...when(field.skipNone)(() => ["skip_serializing_if = \"Option::is_none\""])];
544
+ };
545
+ const spectaParts = (style) => (field) => {
546
+ const override = rustType(style.specta(field.ty));
547
+ return when(override !== rustType(field.ty))(() => [`type = ${override}`]);
548
+ };
549
+ const fieldLines = (style) => (field) => [
550
+ ...docLines(style.indent)(field.doc),
551
+ ...attribute({
552
+ name: "serde",
553
+ parts: serdeParts(style.camel)(field),
554
+ indent: style.indent
555
+ }),
556
+ ...attribute({
557
+ name: "specta",
558
+ parts: spectaParts(style)(field),
559
+ indent: style.indent
560
+ }),
561
+ `${style.indent}${style.visibility}${field.rust}: ${rustType(field.ty)},`
562
+ ];
563
+ const renameAllCamel = (camel) => when(camel)(() => ["rename_all = \"camelCase\""]);
564
+ // src/features/render-rust/model/render-items.ts
565
+ const COMPARABLE = [
566
+ "Debug",
567
+ "Clone",
568
+ "PartialEq"
569
+ ];
570
+ const EQ = [...COMPARABLE, "Eq"];
571
+ const COPY = [
572
+ "Debug",
573
+ "Clone",
574
+ "Copy",
575
+ "PartialEq",
576
+ "Eq",
577
+ "Hash"
578
+ ];
579
+ const FIELD = " ";
580
+ const VARIANT_FIELD = " ";
581
+ const dataDerive = (style) => (name) => style.derive(Match.value(style.hasFloat(name)).pipe(Match.when(true, () => COMPARABLE), Match.orElse(() => EQ)));
582
+ const struct = (style) => (item) => {
583
+ const camel = camelCased(item.fields);
584
+ const lines = fieldLines({
585
+ specta: style.specta,
586
+ visibility: "pub ",
587
+ indent: FIELD,
588
+ camel
589
+ });
590
+ return [
591
+ ...docLines("")(item.doc),
592
+ dataDerive(style)(item.name),
593
+ ...attribute({
594
+ name: "serde",
595
+ parts: renameAllCamel(camel),
596
+ indent: ""
597
+ }),
598
+ `pub struct ${item.name} {`,
599
+ ...pipe(item.fields, Array.flatMap(lines)),
600
+ "}"
601
+ ];
602
+ };
603
+ const STRUCT_VARIANT_WIDTH = 35;
604
+ const MAX_WIDTH = 100;
605
+ const ONE_LINE_PUNCTUATION = 6;
606
+ const SINGLE_LINE = 1;
607
+ const TRAILING_COMMA = /,$/u;
608
+ const laidOut = (style, perVariant) => ([entry, name]) => {
609
+ const lines = fieldLines({
610
+ specta: style.specta,
611
+ visibility: "",
612
+ indent: VARIANT_FIELD,
613
+ camel: camelCased(entry.fields)
614
+ });
615
+ return {
616
+ head: [...docLines(FIELD)(entry.doc), ...attribute({
617
+ name: "serde",
618
+ parts: [...perVariant(entry.value), ...renameAllCamel(camelCased(entry.fields))],
619
+ indent: FIELD
620
+ })],
621
+ name,
622
+ fields: pipe(entry.fields, Array.map(lines))
623
+ };
624
+ };
625
+ const oneLineText = ({ fields }) => pipe(fields, Array.flatMap((lines) => lines), Array.map((line) => pipe(line, String.trim, String.replace(TRAILING_COMMA, ""))), Array.join(", "));
626
+ const isUnit = ({ fields }) => Array.isReadonlyArrayEmpty(fields);
627
+ const fitsOneLine = (laid) => {
628
+ const text = oneLineText(laid);
629
+ const plain = pipe(laid.fields, Array.every((lines) => lines.length === SINGLE_LINE));
630
+ const width = 4 + laid.name.length + text.length + ONE_LINE_PUNCTUATION;
631
+ return plain && text.length <= STRUCT_VARIANT_WIDTH && width <= MAX_WIDTH;
632
+ };
633
+ const isMultiLine = (laid) => Array.isReadonlyArrayNonEmpty(laid.head) || !isUnit(laid) && !fitsOneLine(laid);
634
+ const bodyOf = (vertical) => (laid) => Match.value({
635
+ unit: isUnit(laid),
636
+ oneLine: !vertical && fitsOneLine(laid)
637
+ }).pipe(Match.when({ unit: true }, () => [`${FIELD}${laid.name},`]), Match.when({ oneLine: true }, () => [`${FIELD}${laid.name} { ${oneLineText(laid)} },`]), Match.orElse(() => [
638
+ `${FIELD}${laid.name} {`,
639
+ ...pipe(laid.fields, Array.flatMap((lines) => lines)),
640
+ `${FIELD}},`
641
+ ]));
642
+ const tagged = (style) => (item) => {
643
+ const variants = variantsOf(pipe(item.variants, Array.map(({ value }) => value)));
644
+ const naming = variantNaming(variants);
645
+ const laid = pipe(item.variants, Array.zipWith(variants, (entry, { variant: name }) => [entry, name]), Array.map(laidOut(style, naming.perVariant)));
646
+ const vertical = pipe(laid, Array.some(isMultiLine)) && !pipe(laid, Array.every(isMultiLine));
647
+ return [
648
+ ...docLines("")(item.doc),
649
+ dataDerive(style)(item.name),
650
+ ...attribute({
651
+ name: "serde",
652
+ parts: [`tag = "${escape(item.tag)}"`, ...naming.renameAll],
653
+ indent: ""
654
+ }),
655
+ `pub enum ${item.name} {`,
656
+ ...pipe(laid, Array.flatMap((entry) => pipe(entry.head, Array.appendAll(bodyOf(vertical)(entry))))),
657
+ "}"
658
+ ];
659
+ };
660
+ const itemLines = (style) => {
661
+ const enumeration = enumLines(style.derive(COPY));
662
+ const structure = struct(style);
663
+ const union = tagged(style);
664
+ return (item) => Match.value(item).pipe(Match.tagsExhaustive({
665
+ Struct: structure,
666
+ Tagged: union,
667
+ Enumeration: enumeration,
668
+ Alias: ({ name, doc, ty }) => [...docLines("")(doc), `pub type ${name} = ${rustType(ty)};`]
669
+ }));
670
+ };
671
+ // src/features/render-rust/model/render.ts
672
+ const SPECTA_TYPE = "specta::Type";
673
+ const PATH_SEPARATOR = "::";
674
+ const tysOf = (item) => Match.value(item).pipe(Match.tagsExhaustive({
675
+ Struct: ({ fields }) => pipe(fields, Array.map(({ ty }) => ty)),
676
+ Tagged: ({ variants }) => pipe(variants, Array.flatMap(({ fields }) => fields), Array.map(({ ty }) => ty)),
677
+ Enumeration: () => [],
678
+ Alias: ({ ty }) => [ty]
679
+ }));
680
+ const directFloat = (isFloat) => (ty) => Match.value(ty).pipe(Match.tag("Prim", ({ name }) => name === "f64"), Match.tag("Named", ({ name }) => isFloat(name)), Match.orElse(() => false));
681
+ const itemHasFloat = (isFloat) => {
682
+ const floatTy = someTy(directFloat(isFloat));
683
+ return (item) => pipe(tysOf(item), Array.some(floatTy));
684
+ };
685
+ const floatsIn = (items) => {
686
+ const byName = new Map(pipe(items, Array.map((item) => [item.name, item])));
687
+ const memo = /* @__PURE__ */ new Map();
688
+ const isFloat = (name) => pipe(Option.fromNullishOr(memo.get(name)), Option.getOrElse(() => {
689
+ memo.set(name, false);
690
+ const result = pipe(Option.fromNullishOr(byName.get(name)), Option.exists(itemHasFloat(isFloat)));
691
+ memo.set(name, result);
692
+ return result;
693
+ }));
694
+ return isFloat;
695
+ };
696
+ const constantLine = ({ name, value }) => {
697
+ const rustName = screamingSnakeCase(name);
698
+ return Match.value(value).pipe(Match.when(Predicate.isString, (text) => `pub const ${rustName}: &str = "${escape(text)}";`), Match.when(Predicate.isBoolean, (flag) => `pub const ${rustName}: bool = ${globalThis.String(flag)};`), Match.when(Number.isInteger, (count) => `pub const ${rustName}: i64 = ${globalThis.String(count)};`), Match.orElse((amount) => `pub const ${rustName}: f64 = ${globalThis.String(amount)};`));
699
+ };
700
+ const isMap = (ty) => Predicate.isTagged(ty, "Dictionary");
701
+ const usesMap = (items) => pipe(items, Array.flatMap(tysOf), Array.some(someTy(isMap)));
702
+ const derivePaths = (derive) => pipe(derive, Array.filter(String.includes(PATH_SEPARATOR)));
703
+ const namesType = (name) => (ty) => Predicate.isTagged(ty, "Named") && ty.name === name;
704
+ const usedBy = (tys) => ([name]) => {
705
+ const named = someTy(namesType(name));
706
+ return pipe(tys, Array.some(named));
707
+ };
708
+ const usedExternals = ({ items, external }) => {
709
+ const used = usedBy(pipe(items, Array.flatMap(tysOf)));
710
+ return pipe(Record.toEntries(external), Array.filter(used), Array.map(([, path]) => path));
711
+ };
712
+ const importLines = (rendering) => {
713
+ const { items, derive } = rendering;
714
+ return pipe(when(Array.isReadonlyArrayNonEmpty(items))(() => [
715
+ "serde::{Deserialize, Serialize}",
716
+ ...derivePaths(derive),
717
+ ...when(usesMap(items))(() => ["std::collections::BTreeMap"]),
718
+ ...usedExternals(rendering)
719
+ ]), Array.sortBy(String.Order), Array.map((path) => `use ${path};`));
720
+ };
721
+ const aliasesOf = (items) => new Map(pipe(items, Array.flatMap((item) => Match.value(item).pipe(Match.tag("Alias", ({ name, ty }) => [[name, ty]]), Match.orElse(() => [])))));
722
+ const spectaOf = ({ derive, items, imported }) => {
723
+ const aliases = aliasesOf([...items, ...imported]);
724
+ return Match.value(pipe(derive, Array.contains(SPECTA_TYPE))).pipe(Match.when(true, () => spectaType((name) => Option.fromNullishOr(aliases.get(name)))), Match.orElse(() => (ty) => ty));
725
+ };
726
+ const shortName = (path) => pipe(path, String.split(PATH_SEPARATOR), Array.lastNonEmpty);
727
+ const deriveLine = (extra) => (base) => `#[derive(${pipe([
728
+ ...base,
729
+ "Serialize",
730
+ "Deserialize",
731
+ ...extra
732
+ ], Array.join(", "))})]`;
733
+ const render = (rendering) => {
734
+ const extra = pipe(rendering.derive, Array.map(shortName));
735
+ const lines = itemLines({
736
+ derive: deriveLine(extra),
737
+ specta: spectaOf(rendering),
738
+ hasFloat: floatsIn([...rendering.items, ...rendering.imported])
739
+ });
740
+ const sections = pipe([
741
+ [rendering.header],
742
+ importLines(rendering),
743
+ pipe(rendering.constants, Array.map(constantLine)),
744
+ ...pipe(rendering.items, Array.map(lines))
745
+ ], Array.filter(Array.isReadonlyArrayNonEmpty), Array.map(Array.join("\n")));
746
+ return `${pipe(sections, Array.join("\n\n"))}\n`;
747
+ };
748
+ // src/app/effect2rs.ts
749
+ const isConstant = Predicate.or(Predicate.isString, Predicate.or(Predicate.isNumber, Predicate.isBoolean));
750
+ const NAMED_BY_EXPORT = [
751
+ SchemaAST.isObjects,
752
+ SchemaAST.isUnion,
753
+ SchemaAST.isEnum,
754
+ SchemaAST.isDeclaration,
755
+ SchemaAST.isArrays,
756
+ SchemaAST.isSuspend
757
+ ];
758
+ const namedByExport = (ast) => pipe(NAMED_BY_EXPORT, Array.some((guard) => guard(ast)));
759
+ const isGenerated = (ast) => namedByExport(ast) || Predicate.isString(SchemaAST.resolveIdentifier(ast));
760
+ const constantOf = ([key, value]) => pipe(Option.liftPredicate(value, isConstant), Option.match({
761
+ onNone: () => Effect.fail(UnsupportedSchema.make({
762
+ path: key,
763
+ reason: "exports must be schemas, strings, numbers, or booleans"
764
+ })),
765
+ onSome: (constant) => Effect.succeed({
766
+ name: key,
767
+ value: constant
768
+ })
769
+ }));
770
+ const schemasOf = (definitions) => pipe(Record.toEntries(definitions), Array.filter((entry) => {
771
+ const [, value] = entry;
772
+ return Schema.isSchema(value);
773
+ }));
774
+ const documentOf = (definitions) => {
775
+ const schemas = schemasOf(definitions);
776
+ const exported = new Map(pipe(schemas, Array.filter(([, schema]) => namedByExport(schema.ast)), Array.map(([key, schema]) => [schema.ast, key])));
777
+ const chosen = /* @__PURE__ */ new Set();
778
+ const policy = ({ ast, identifier }) => pipe(Option.fromNullishOr(identifier), Option.orElse(() => Option.fromNullishOr(exported.get(ast))), Option.tap((name) => Option.some(chosen.add(name))), Option.getOrUndefined);
779
+ return {
780
+ references: pipe(schemas, Array.map(([, schema]) => schema.ast), Array.filter(isGenerated), Array.match({
781
+ onEmpty: () => ({}),
782
+ onNonEmpty: (asts) => SchemaRepresentation.toRepresentations(asts, { referencePolicy: policy }).references
783
+ })),
784
+ chosen
785
+ };
786
+ };
787
+ const renamed = (name) => UnsupportedSchema.make({
788
+ path: name,
789
+ reason: "another schema has the same name, or a recursive schema has no identifier"
790
+ });
791
+ const effect2rs = Effect.fn("effect2rs")(function* effect2rs(input) {
792
+ const constants = yield* pipe(Record.toEntries(input.definitions), Array.filter(([, value]) => !Schema.isSchema(value)), (items) => Effect.forEach(items, constantOf, { concurrency: 1 }));
793
+ const { references, chosen } = documentOf(input.definitions);
794
+ const named = Record.toEntries(references);
795
+ yield* pipe(named, Array.findFirst(([name]) => !chosen.has(name)), Option.match({
796
+ onNone: () => Effect.void,
797
+ onSome: ([name]) => Effect.fail(renamed(name))
798
+ }));
799
+ const items = yield* Effect.forEach(named, itemOf(references), { concurrency: 1 });
800
+ const external = input.external ?? {};
801
+ return render({
802
+ header: input.header,
803
+ derive: input.derive ?? [],
804
+ items: pipe(items, Array.filter(({ name }) => !Record.has(external, name))),
805
+ imported: pipe(items, Array.filter(({ name }) => Record.has(external, name))),
806
+ external,
807
+ constants
808
+ });
809
+ });
810
+ const checkRust = Effect.fn("effect2rs.checkRust")(function* checkRust(check) {
811
+ const source = yield* effect2rs(check);
812
+ yield* pipe(check.current, Option.filter((current) => current === source), Option.match({
813
+ onNone: () => Effect.fail(staleRust(check.path)),
814
+ onSome: () => Effect.void
815
+ }));
816
+ return yield* pipe(copiesOf(source)(check.siblings), Array.match({
817
+ onEmpty: () => Effect.void,
818
+ onNonEmpty: (copies) => Effect.fail(handWrittenCopies(copies))
819
+ }));
820
+ });
821
+ const RUST_FILE = ".rs";
822
+ const readRust = Effect.fn("effect2rs.readRust")(function* readRust(file) {
823
+ return {
824
+ path: file,
825
+ source: yield* (yield* FileSystem.FileSystem).readFileString(file)
826
+ };
827
+ });
828
+ const siblingsOf = Effect.fn("effect2rs.siblingsOf")(function* siblingsOf(output) {
829
+ const fileSystem = yield* FileSystem.FileSystem;
830
+ const path = yield* Path.Path;
831
+ const directory = path.dirname(output);
832
+ const entries = yield* fileSystem.readDirectory(directory, { recursive: true });
833
+ const files = pipe(entries, Array.filter(String.endsWith(RUST_FILE)), Array.map((entry) => path.join(directory, entry)), Array.filter((file) => path.resolve(file) !== path.resolve(output)), Array.sortBy(String.Order));
834
+ return yield* Effect.forEach(files, readRust, { concurrency: 1 });
835
+ });
836
+ const writeRust = Effect.fn("effect2rs.writeRust")(function* writeRust(target) {
837
+ const fileSystem = yield* FileSystem.FileSystem;
838
+ const path = yield* Path.Path;
839
+ const source = yield* effect2rs(target);
840
+ yield* fileSystem.makeDirectory(path.dirname(target.output), { recursive: true });
841
+ yield* fileSystem.writeFileString(target.output, source);
842
+ });
843
+ const checkRustOutput = Effect.fn("effect2rs.checkRustOutput")(function* checkRustOutput(target) {
844
+ const fileSystem = yield* FileSystem.FileSystem;
845
+ const current = yield* Effect.option(fileSystem.readFileString(target.output));
846
+ const siblings = yield* siblingsOf(target.output);
847
+ yield* checkRust({
848
+ ...target,
849
+ path: target.output,
850
+ current,
851
+ siblings
852
+ });
853
+ });
854
+ /** @stability experimental */
855
+ const syncRust = Effect.fn("effect2rs.syncRust")(function* syncRust(outputs, options) {
856
+ if (options.check) {
857
+ yield* Effect.forEach(outputs, checkRustOutput, {
858
+ concurrency: 1,
859
+ discard: true
860
+ });
861
+ return;
862
+ }
863
+ yield* Effect.forEach(outputs, writeRust, {
864
+ concurrency: 1,
865
+ discard: true
866
+ });
867
+ });
868
+ export { HandWrittenCopies, StaleRust, UnsupportedSchema, checkRust, effect2rs, syncRust };
869
+
870
+ //# sourceMappingURL=effect2rs.mjs.map