@sundaeswap/sprinkles 0.4.0 → 0.6.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 (140) hide show
  1. package/dist/cjs/Sprinkle/__tests__/encryption.test.js +22 -8
  2. package/dist/cjs/Sprinkle/__tests__/encryption.test.js.map +1 -1
  3. package/dist/cjs/Sprinkle/__tests__/enhancements.test.js +37 -46
  4. package/dist/cjs/Sprinkle/__tests__/enhancements.test.js.map +1 -1
  5. package/dist/cjs/Sprinkle/__tests__/field-utils.test.js +170 -0
  6. package/dist/cjs/Sprinkle/__tests__/field-utils.test.js.map +1 -0
  7. package/dist/cjs/Sprinkle/__tests__/fill-in-struct.test.js +283 -81
  8. package/dist/cjs/Sprinkle/__tests__/fill-in-struct.test.js.map +1 -1
  9. package/dist/cjs/Sprinkle/__tests__/formatting.test.js +97 -0
  10. package/dist/cjs/Sprinkle/__tests__/formatting.test.js.map +1 -0
  11. package/dist/cjs/Sprinkle/__tests__/show-menu.test.js +97 -7
  12. package/dist/cjs/Sprinkle/__tests__/show-menu.test.js.map +1 -1
  13. package/dist/cjs/Sprinkle/__tests__/tx-dialog.test.js +30 -0
  14. package/dist/cjs/Sprinkle/__tests__/tx-dialog.test.js.map +1 -1
  15. package/dist/cjs/Sprinkle/encryption.js +131 -0
  16. package/dist/cjs/Sprinkle/encryption.js.map +1 -0
  17. package/dist/cjs/Sprinkle/index.js +427 -438
  18. package/dist/cjs/Sprinkle/index.js.map +1 -1
  19. package/dist/cjs/Sprinkle/menus/array-menu.js +195 -0
  20. package/dist/cjs/Sprinkle/menus/array-menu.js.map +1 -0
  21. package/dist/cjs/Sprinkle/menus/field-menu.js +161 -0
  22. package/dist/cjs/Sprinkle/menus/field-menu.js.map +1 -0
  23. package/dist/cjs/Sprinkle/menus/index.js +33 -0
  24. package/dist/cjs/Sprinkle/menus/index.js.map +1 -0
  25. package/dist/cjs/Sprinkle/menus/object-menu.js +324 -0
  26. package/dist/cjs/Sprinkle/menus/object-menu.js.map +1 -0
  27. package/dist/cjs/Sprinkle/prompts.js +459 -0
  28. package/dist/cjs/Sprinkle/prompts.js.map +1 -0
  29. package/dist/cjs/Sprinkle/schemas.js +97 -0
  30. package/dist/cjs/Sprinkle/schemas.js.map +1 -0
  31. package/dist/cjs/Sprinkle/tx-dialog.js +101 -0
  32. package/dist/cjs/Sprinkle/tx-dialog.js.map +1 -0
  33. package/dist/cjs/Sprinkle/type-guards.js +89 -0
  34. package/dist/cjs/Sprinkle/type-guards.js.map +1 -0
  35. package/dist/cjs/Sprinkle/types.js +73 -0
  36. package/dist/cjs/Sprinkle/types.js.map +1 -0
  37. package/dist/cjs/Sprinkle/utils/field-utils.js +154 -0
  38. package/dist/cjs/Sprinkle/utils/field-utils.js.map +1 -0
  39. package/dist/cjs/Sprinkle/utils/formatting.js +126 -0
  40. package/dist/cjs/Sprinkle/utils/formatting.js.map +1 -0
  41. package/dist/cjs/Sprinkle/utils/index.js +56 -0
  42. package/dist/cjs/Sprinkle/utils/index.js.map +1 -0
  43. package/dist/cjs/Sprinkle/wallet.js +98 -0
  44. package/dist/cjs/Sprinkle/wallet.js.map +1 -0
  45. package/dist/esm/Sprinkle/__tests__/encryption.test.js +22 -8
  46. package/dist/esm/Sprinkle/__tests__/encryption.test.js.map +1 -1
  47. package/dist/esm/Sprinkle/__tests__/enhancements.test.js +37 -46
  48. package/dist/esm/Sprinkle/__tests__/enhancements.test.js.map +1 -1
  49. package/dist/esm/Sprinkle/__tests__/field-utils.test.js +168 -0
  50. package/dist/esm/Sprinkle/__tests__/field-utils.test.js.map +1 -0
  51. package/dist/esm/Sprinkle/__tests__/fill-in-struct.test.js +284 -82
  52. package/dist/esm/Sprinkle/__tests__/fill-in-struct.test.js.map +1 -1
  53. package/dist/esm/Sprinkle/__tests__/formatting.test.js +95 -0
  54. package/dist/esm/Sprinkle/__tests__/formatting.test.js.map +1 -0
  55. package/dist/esm/Sprinkle/__tests__/show-menu.test.js +98 -8
  56. package/dist/esm/Sprinkle/__tests__/show-menu.test.js.map +1 -1
  57. package/dist/esm/Sprinkle/__tests__/tx-dialog.test.js +30 -0
  58. package/dist/esm/Sprinkle/__tests__/tx-dialog.test.js.map +1 -1
  59. package/dist/esm/Sprinkle/encryption.js +117 -0
  60. package/dist/esm/Sprinkle/encryption.js.map +1 -0
  61. package/dist/esm/Sprinkle/index.js +248 -425
  62. package/dist/esm/Sprinkle/index.js.map +1 -1
  63. package/dist/esm/Sprinkle/menus/array-menu.js +190 -0
  64. package/dist/esm/Sprinkle/menus/array-menu.js.map +1 -0
  65. package/dist/esm/Sprinkle/menus/field-menu.js +155 -0
  66. package/dist/esm/Sprinkle/menus/field-menu.js.map +1 -0
  67. package/dist/esm/Sprinkle/menus/index.js +8 -0
  68. package/dist/esm/Sprinkle/menus/index.js.map +1 -0
  69. package/dist/esm/Sprinkle/menus/object-menu.js +318 -0
  70. package/dist/esm/Sprinkle/menus/object-menu.js.map +1 -0
  71. package/dist/esm/Sprinkle/prompts.js +443 -0
  72. package/dist/esm/Sprinkle/prompts.js.map +1 -0
  73. package/dist/esm/Sprinkle/schemas.js +91 -0
  74. package/dist/esm/Sprinkle/schemas.js.map +1 -0
  75. package/dist/esm/Sprinkle/tx-dialog.js +90 -0
  76. package/dist/esm/Sprinkle/tx-dialog.js.map +1 -0
  77. package/dist/esm/Sprinkle/type-guards.js +66 -0
  78. package/dist/esm/Sprinkle/type-guards.js.map +1 -0
  79. package/dist/esm/Sprinkle/types.js +66 -0
  80. package/dist/esm/Sprinkle/types.js.map +1 -0
  81. package/dist/esm/Sprinkle/utils/field-utils.js +145 -0
  82. package/dist/esm/Sprinkle/utils/field-utils.js.map +1 -0
  83. package/dist/esm/Sprinkle/utils/formatting.js +118 -0
  84. package/dist/esm/Sprinkle/utils/formatting.js.map +1 -0
  85. package/dist/esm/Sprinkle/utils/index.js +7 -0
  86. package/dist/esm/Sprinkle/utils/index.js.map +1 -0
  87. package/dist/esm/Sprinkle/wallet.js +90 -0
  88. package/dist/esm/Sprinkle/wallet.js.map +1 -0
  89. package/dist/types/Sprinkle/encryption.d.ts +43 -0
  90. package/dist/types/Sprinkle/encryption.d.ts.map +1 -0
  91. package/dist/types/Sprinkle/index.d.ts +17 -177
  92. package/dist/types/Sprinkle/index.d.ts.map +1 -1
  93. package/dist/types/Sprinkle/menus/array-menu.d.ts +31 -0
  94. package/dist/types/Sprinkle/menus/array-menu.d.ts.map +1 -0
  95. package/dist/types/Sprinkle/menus/field-menu.d.ts +34 -0
  96. package/dist/types/Sprinkle/menus/field-menu.d.ts.map +1 -0
  97. package/dist/types/Sprinkle/menus/index.d.ts +10 -0
  98. package/dist/types/Sprinkle/menus/index.d.ts.map +1 -0
  99. package/dist/types/Sprinkle/menus/object-menu.d.ts +34 -0
  100. package/dist/types/Sprinkle/menus/object-menu.d.ts.map +1 -0
  101. package/dist/types/Sprinkle/prompts.d.ts +119 -0
  102. package/dist/types/Sprinkle/prompts.d.ts.map +1 -0
  103. package/dist/types/Sprinkle/schemas.d.ts +125 -0
  104. package/dist/types/Sprinkle/schemas.d.ts.map +1 -0
  105. package/dist/types/Sprinkle/tx-dialog.d.ts +37 -0
  106. package/dist/types/Sprinkle/tx-dialog.d.ts.map +1 -0
  107. package/dist/types/Sprinkle/type-guards.d.ts +45 -0
  108. package/dist/types/Sprinkle/type-guards.d.ts.map +1 -0
  109. package/dist/types/Sprinkle/types.d.ts +115 -0
  110. package/dist/types/Sprinkle/types.d.ts.map +1 -0
  111. package/dist/types/Sprinkle/utils/field-utils.d.ts +47 -0
  112. package/dist/types/Sprinkle/utils/field-utils.d.ts.map +1 -0
  113. package/dist/types/Sprinkle/utils/formatting.d.ts +30 -0
  114. package/dist/types/Sprinkle/utils/formatting.d.ts.map +1 -0
  115. package/dist/types/Sprinkle/wallet.d.ts +27 -0
  116. package/dist/types/Sprinkle/wallet.d.ts.map +1 -0
  117. package/dist/types/tsconfig.build.tsbuildinfo +1 -1
  118. package/package.json +1 -1
  119. package/src/Sprinkle/__tests__/encryption.test.ts +23 -8
  120. package/src/Sprinkle/__tests__/enhancements.test.ts +34 -47
  121. package/src/Sprinkle/__tests__/field-utils.test.ts +191 -0
  122. package/src/Sprinkle/__tests__/fill-in-struct.test.ts +301 -86
  123. package/src/Sprinkle/__tests__/formatting.test.ts +115 -0
  124. package/src/Sprinkle/__tests__/show-menu.test.ts +102 -8
  125. package/src/Sprinkle/__tests__/tx-dialog.test.ts +30 -0
  126. package/src/Sprinkle/encryption.ts +130 -0
  127. package/src/Sprinkle/index.ts +368 -598
  128. package/src/Sprinkle/menus/array-menu.ts +191 -0
  129. package/src/Sprinkle/menus/field-menu.ts +145 -0
  130. package/src/Sprinkle/menus/index.ts +12 -0
  131. package/src/Sprinkle/menus/object-menu.ts +336 -0
  132. package/src/Sprinkle/prompts.ts +551 -0
  133. package/src/Sprinkle/schemas.ts +111 -0
  134. package/src/Sprinkle/tx-dialog.ts +100 -0
  135. package/src/Sprinkle/type-guards.ts +93 -0
  136. package/src/Sprinkle/types.ts +116 -0
  137. package/src/Sprinkle/utils/field-utils.ts +158 -0
  138. package/src/Sprinkle/utils/formatting.ts +127 -0
  139. package/src/Sprinkle/utils/index.ts +17 -0
  140. package/src/Sprinkle/wallet.ts +133 -0
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Transaction dialog helper utilities.
3
+ * Functions for working with transaction signatures and display.
4
+ */
5
+
6
+ import { Core, HotWallet } from "@blaze-cardano/sdk";
7
+ import { CborSet, VkeyWitness, blake2b_256 } from "@blaze-cardano/core";
8
+
9
+ /**
10
+ * Get the payment key hash from a HotWallet's first address.
11
+ */
12
+ export async function getWalletPaymentKeyHash(
13
+ wallet: HotWallet,
14
+ ): Promise<string | null> {
15
+ try {
16
+ const addresses = await wallet.getUsedAddresses();
17
+ const address = addresses[0];
18
+ if (!address) return null;
19
+ const paymentCredential = address.asBase()?.getPaymentCredential();
20
+ return paymentCredential?.hash?.toString() ?? null;
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Count the number of vkey signatures in a transaction's witness set.
28
+ */
29
+ export function countSignatures(tx: Core.Transaction): number {
30
+ const vkeys = tx.witnessSet().vkeys();
31
+ return vkeys ? vkeys.size() : 0;
32
+ }
33
+
34
+ /**
35
+ * Check if a specific public key has already signed the transaction.
36
+ * Compares by vkey (public key bytes).
37
+ */
38
+ export function hasVkeySigned(tx: Core.Transaction, vkeyHex: string): boolean {
39
+ const vkeys = tx.witnessSet().vkeys();
40
+ if (!vkeys) return false;
41
+ const vkeyArray = vkeys.toCore();
42
+ return vkeyArray.some(([vkey]) => vkey === vkeyHex);
43
+ }
44
+
45
+ /**
46
+ * Get the list of required signer key hashes from the transaction body.
47
+ */
48
+ export function getRequiredSigners(tx: Core.Transaction): string[] {
49
+ const requiredSigners = tx.body().requiredSigners();
50
+ if (!requiredSigners) return [];
51
+ return Array.from(requiredSigners.values()).map((s) => s.toString());
52
+ }
53
+
54
+ /**
55
+ * Compute the transaction body hash for display.
56
+ */
57
+ export function getTxBodyHash(tx: Core.Transaction): string {
58
+ const bodyCbor = tx.body().toCbor();
59
+ return blake2b_256(bodyCbor);
60
+ }
61
+
62
+ /**
63
+ * Format a hash for display: first 8 chars + ... + last 8 chars.
64
+ */
65
+ export function formatHash(hash: string): string {
66
+ if (hash.length <= 20) return hash;
67
+ return `${hash.slice(0, 8)}...${hash.slice(-8)}`;
68
+ }
69
+
70
+ /**
71
+ * Merge signatures from source transaction into target transaction.
72
+ * Prevents duplicate signatures by comparing vkey (public key).
73
+ * Returns the count of newly added signatures.
74
+ */
75
+ export function mergeSignatures(
76
+ target: Core.Transaction,
77
+ source: Core.Transaction,
78
+ ): number {
79
+ const targetWs = target.witnessSet();
80
+ const sourceWs = source.witnessSet();
81
+
82
+ const targetVkeys = targetWs.vkeys()?.toCore() ?? [];
83
+ const sourceVkeys = sourceWs.vkeys()?.toCore() ?? [];
84
+
85
+ // Find vkeys in source that aren't in target (by comparing public key)
86
+ const existingPubKeys = new Set(targetVkeys.map(([vkey]) => vkey));
87
+ const newVkeys = sourceVkeys.filter(([vkey]) => !existingPubKeys.has(vkey));
88
+
89
+ if (newVkeys.length === 0) {
90
+ return 0;
91
+ }
92
+
93
+ // Merge the new vkeys into target
94
+ targetWs.setVkeys(
95
+ CborSet.fromCore([...targetVkeys, ...newVkeys], VkeyWitness.fromCore),
96
+ );
97
+ target.setWitnessSet(targetWs);
98
+
99
+ return newVkeys.length;
100
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Type guard utilities for TypeBox schema types.
3
+ * These are internal helpers used by FillInStruct, encryption, and other modules.
4
+ */
5
+
6
+ import {
7
+ Kind,
8
+ type TBigInt,
9
+ type TLiteral,
10
+ type TNull,
11
+ type TObject,
12
+ type TSchema,
13
+ type TString,
14
+ type TTuple,
15
+ type TUnion,
16
+ type TArray,
17
+ type TThis,
18
+ type TRef,
19
+ type TImport,
20
+ type TOptional,
21
+ type Static,
22
+ OptionalKind,
23
+ } from "@sinclair/typebox";
24
+
25
+ export const isOptional = <T extends TSchema>(t: T): t is TOptional<T> =>
26
+ t[OptionalKind] === "Optional";
27
+
28
+ export const isImport = (t: TSchema): t is TImport => t[Kind] === "Import";
29
+
30
+ export const isArray = (t: TSchema): t is TArray => t[Kind] === "Array";
31
+
32
+ export const isBigInt = (t: TSchema): t is TBigInt => t[Kind] === "BigInt";
33
+
34
+ export const isLiteral = (t: TSchema): t is TLiteral => t[Kind] === "Literal";
35
+
36
+ export const isObject = (t: TSchema): t is TObject => t[Kind] === "Object";
37
+
38
+ export const isRef = (t: TSchema): t is TRef => t[Kind] === "Ref";
39
+
40
+ export const isString = (t: TSchema): t is TString => t[Kind] === "String";
41
+
42
+ export const isThis = (t: TSchema): t is TThis => t[Kind] === "This";
43
+
44
+ export const isTuple = (t: TSchema): t is TTuple => t[Kind] === "Tuple";
45
+
46
+ export const isUnion = (t: TSchema): t is TUnion => t[Kind] === "Union";
47
+
48
+ /**
49
+ * Check if a schema field is marked as sensitive.
50
+ * Sensitive fields are encrypted when saved and masked when displayed.
51
+ */
52
+ export const isSensitive = (t: TSchema): boolean =>
53
+ isString(t) && t.sensitive === true;
54
+
55
+ /**
56
+ * Check if a schema is a Null type.
57
+ */
58
+ export const isNull = (t: TSchema): t is TNull => t[Kind] === "Null";
59
+
60
+ /**
61
+ * Check if a schema allows null values.
62
+ * Returns true for TNull or unions containing TNull.
63
+ */
64
+ export const isNullable = (t: TSchema): boolean => {
65
+ if (isNull(t)) return true;
66
+ if (isUnion(t)) return t.anyOf.some((member) => isNull(member));
67
+ return false;
68
+ };
69
+
70
+ /**
71
+ * Unwrap a nullable type to get the non-null inner type.
72
+ * For unions with Null, returns the union without the Null member.
73
+ * For single non-null member unions, returns just that type.
74
+ */
75
+ export const unwrapNullable = (t: TSchema): TSchema => {
76
+ if (isUnion(t)) {
77
+ const nonNull = t.anyOf.filter((member) => !isNull(member));
78
+ if (nonNull.length === 1) return nonNull[0]!;
79
+ return { ...t, anyOf: nonNull } as TSchema;
80
+ }
81
+ return t;
82
+ };
83
+
84
+ /**
85
+ * Check if a schema has a default value defined.
86
+ */
87
+ export const hasDefault = (t: TSchema): boolean => "default" in t;
88
+
89
+ /**
90
+ * Get the default value from a schema, if defined.
91
+ */
92
+ export const getDefault = <T extends TSchema>(t: T): Static<T> | undefined =>
93
+ t.default as Static<T> | undefined;
@@ -0,0 +1,116 @@
1
+ import { Core } from "@blaze-cardano/sdk";
2
+ import type { Static, TSchema } from "@sinclair/typebox";
3
+
4
+ /**
5
+ * Utility type to extract the static type from a TypeBox schema.
6
+ */
7
+ export type TExact<T> = T extends TSchema ? Static<T> : T;
8
+
9
+ /**
10
+ * Options for encrypting/decrypting sensitive fields in settings.
11
+ */
12
+ export interface IEncryptionOptions {
13
+ encrypt: (plaintext: string) => string;
14
+ decrypt: (ciphertext: string) => Promise<string>;
15
+ }
16
+
17
+ /**
18
+ * Options for configuring a Sprinkle instance.
19
+ */
20
+ export interface ISprinkleOptions {
21
+ encryption?: IEncryptionOptions;
22
+ }
23
+
24
+ /**
25
+ * Metadata for a profile.
26
+ */
27
+ export interface IProfileMeta {
28
+ name: string;
29
+ description?: string;
30
+ createdAt: string;
31
+ updatedAt: string;
32
+ }
33
+
34
+ /**
35
+ * Current profile information including ID.
36
+ */
37
+ export interface ICurrentProfile extends IProfileMeta {
38
+ id: string;
39
+ }
40
+
41
+ /**
42
+ * Profile entry as returned by scanProfiles().
43
+ */
44
+ export interface IProfileEntry {
45
+ id: string;
46
+ meta: IProfileMeta;
47
+ }
48
+
49
+ /**
50
+ * Result of the TxDialog interaction.
51
+ */
52
+ export interface TxDialogResult {
53
+ action: "submitted" | "signed" | "cancelled";
54
+ txId?: string; // present only if action === 'submitted'
55
+ tx: Core.Transaction; // the (potentially signed) transaction
56
+ }
57
+
58
+ /**
59
+ * Options for TxDialog.
60
+ */
61
+ export interface TxDialogOptions {
62
+ beforeSign?: () => Promise<void>;
63
+ }
64
+
65
+ /**
66
+ * Error thrown when user cancels a prompt via Escape key.
67
+ */
68
+ export class UserCancelledError extends Error {
69
+ constructor(message: string = "User cancelled the operation") {
70
+ super(message);
71
+ this.name = "UserCancelledError";
72
+ }
73
+ }
74
+
75
+ // --- Menu-based FillInStruct types ---
76
+
77
+ /**
78
+ * State tracking for a single field during menu-based editing.
79
+ */
80
+ export type FieldState<T = unknown> =
81
+ | { status: "unset" }
82
+ | { status: "set"; value: T }
83
+ | { status: "null" }; // explicitly set to null
84
+
85
+ /**
86
+ * Result of counting required fields in a schema.
87
+ */
88
+ export interface RequiredFieldCount {
89
+ total: number;
90
+ filled: number;
91
+ }
92
+
93
+ /**
94
+ * Result from field menu interaction.
95
+ */
96
+ export type FieldMenuResult<T = unknown> =
97
+ | { action: "edit" }
98
+ | { action: "view" }
99
+ | { action: "clear" }
100
+ | { action: "setNull" }
101
+ | { action: "reset"; defaultValue: T }
102
+ | { action: "back" };
103
+
104
+ /**
105
+ * Result from object menu interaction.
106
+ */
107
+ export type ObjectMenuResult<T = unknown> =
108
+ | { action: "submit"; value: T }
109
+ | { action: "cancel" };
110
+
111
+ /**
112
+ * Result from array menu interaction.
113
+ */
114
+ export type ArrayMenuResult<T = unknown> =
115
+ | { action: "done"; value: T[] }
116
+ | { action: "back" };
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Field utilities for menu-based struct editing.
3
+ * Provides required field counting and label building.
4
+ */
5
+
6
+ import type { TObject, TSchema } from "@sinclair/typebox";
7
+ import type { FieldState, RequiredFieldCount } from "../types.js";
8
+ import {
9
+ isOptional,
10
+ isNullable,
11
+ hasDefault,
12
+ getDefault,
13
+ isLiteral,
14
+ } from "../type-guards.js";
15
+ import { formatValuePreview } from "./formatting.js";
16
+
17
+ /**
18
+ * Count required fields in an object schema and how many are filled.
19
+ *
20
+ * @param type - The object schema
21
+ * @param state - Map of field names to their current state
22
+ * @returns Count of total required fields and how many are filled
23
+ */
24
+ export function countRequiredFields(
25
+ type: TObject,
26
+ state: Map<string, FieldState>,
27
+ ): RequiredFieldCount {
28
+ const fields = type.properties as Record<string, TSchema>;
29
+ let total = 0;
30
+ let filled = 0;
31
+
32
+ for (const [fieldName, fieldType] of Object.entries(fields)) {
33
+ // Skip optional fields - they're not required
34
+ if (isOptional(fieldType)) {
35
+ continue;
36
+ }
37
+
38
+ // Non-nullable fields with defaults don't require user input
39
+ if (hasDefault(fieldType) && !isNullable(fieldType)) {
40
+ continue;
41
+ }
42
+
43
+ // Literal fields auto-fill, so they're not required from the user
44
+ if (isLiteral(fieldType)) {
45
+ continue;
46
+ }
47
+
48
+ // This is a required field
49
+ total++;
50
+
51
+ // Check if it's filled
52
+ const fieldState = state.get(fieldName);
53
+ if (fieldState?.status === "set" || fieldState?.status === "null") {
54
+ filled++;
55
+ }
56
+ }
57
+
58
+ return { total, filled };
59
+ }
60
+
61
+ /**
62
+ * Determine if a field is required (must have a value to submit).
63
+ *
64
+ * @param fieldType - The field's schema
65
+ * @returns true if the field is required
66
+ */
67
+ export function isFieldRequired(fieldType: TSchema): boolean {
68
+ // Optional fields are not required
69
+ if (isOptional(fieldType)) {
70
+ return false;
71
+ }
72
+
73
+ // Literal fields auto-fill, so they're not required from the user
74
+ if (isLiteral(fieldType)) {
75
+ return false;
76
+ }
77
+
78
+ // Non-nullable fields with defaults are not required (default will be used)
79
+ if (hasDefault(fieldType) && !isNullable(fieldType)) {
80
+ return false;
81
+ }
82
+
83
+ return true;
84
+ }
85
+
86
+ /**
87
+ * Build a display label for a field in the menu.
88
+ *
89
+ * @param fieldName - The field name
90
+ * @param fieldType - The field's schema
91
+ * @param state - The current state of the field
92
+ * @returns Formatted label string
93
+ */
94
+ export function buildFieldLabel(
95
+ fieldName: string,
96
+ fieldType: TSchema,
97
+ state: FieldState,
98
+ ): string {
99
+ const required = isFieldRequired(fieldType);
100
+ const requiredMarker = required ? " *" : "";
101
+
102
+ switch (state.status) {
103
+ case "unset": {
104
+ // Check for default value
105
+ if (hasDefault(fieldType)) {
106
+ const defaultVal = getDefault(fieldType);
107
+ const preview = formatValuePreview(defaultVal, 30);
108
+ return `${fieldName}: [default: ${preview}]${requiredMarker}`;
109
+ }
110
+ return `${fieldName}: [not set]${requiredMarker}`;
111
+ }
112
+
113
+ case "null":
114
+ return `${fieldName}: null${requiredMarker}`;
115
+
116
+ case "set": {
117
+ const preview = formatValuePreview(state.value, 40);
118
+ return `${fieldName}: ${preview}${requiredMarker}`;
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Get the initial FieldState for a field based on its type and any existing value.
125
+ *
126
+ * @param _fieldType - The field's schema (reserved for future logic)
127
+ * @param existingValue - Existing value if editing
128
+ * @returns Initial FieldState
129
+ */
130
+ export function getInitialFieldState<T>(
131
+ _fieldType: TSchema,
132
+ existingValue?: T,
133
+ ): FieldState<T> {
134
+ if (existingValue === undefined) {
135
+ return { status: "unset" };
136
+ }
137
+
138
+ if (existingValue === null) {
139
+ return { status: "null" };
140
+ }
141
+
142
+ return { status: "set", value: existingValue };
143
+ }
144
+
145
+ /**
146
+ * Check if all required fields are filled in the state map.
147
+ *
148
+ * @param type - The object schema
149
+ * @param state - Map of field names to their current state
150
+ * @returns true if all required fields have values
151
+ */
152
+ export function allRequiredFieldsFilled(
153
+ type: TObject,
154
+ state: Map<string, FieldState>,
155
+ ): boolean {
156
+ const { total, filled } = countRequiredFields(type, state);
157
+ return filled >= total;
158
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Formatting utilities for menu-based struct editing.
3
+ * Provides value preview, path formatting, and breadcrumb generation.
4
+ */
5
+
6
+ /**
7
+ * Format a value for display in a menu item.
8
+ * Truncates long values and provides type-appropriate previews.
9
+ *
10
+ * @param value - The value to format
11
+ * @param maxLength - Maximum length before truncation (default 40)
12
+ * @returns Formatted string representation
13
+ */
14
+ export function formatValuePreview(value: unknown, maxLength = 40): string {
15
+ if (value === null) {
16
+ return "null";
17
+ }
18
+
19
+ if (value === undefined) {
20
+ return "[not set]";
21
+ }
22
+
23
+ if (typeof value === "string") {
24
+ const escaped = JSON.stringify(value);
25
+ if (escaped.length <= maxLength) {
26
+ return escaped;
27
+ }
28
+ // Truncate inside the quotes (guard against negative maxLength from recursion)
29
+ return `"${value.slice(0, Math.max(0, maxLength - 5))}..."`;
30
+ }
31
+
32
+ if (typeof value === "number" || typeof value === "bigint") {
33
+ return String(value);
34
+ }
35
+
36
+ if (typeof value === "boolean") {
37
+ return String(value);
38
+ }
39
+
40
+ if (Array.isArray(value)) {
41
+ return `[${value.length} item${value.length === 1 ? "" : "s"}]`;
42
+ }
43
+
44
+ if (typeof value === "object") {
45
+ // For objects, try to show a meaningful preview
46
+ const keys = Object.keys(value);
47
+ if (keys.length === 0) {
48
+ return "{}";
49
+ }
50
+
51
+ // If object has a single key (like union type), show it
52
+ if (keys.length === 1) {
53
+ const key = keys[0]!;
54
+ const innerValue = (value as Record<string, unknown>)[key];
55
+ const innerPreview = formatValuePreview(innerValue, maxLength - key.length - 6);
56
+ const preview = `{ ${key}: ${innerPreview} }`;
57
+ if (preview.length <= maxLength) {
58
+ return preview;
59
+ }
60
+ return `{ ${key}: ... }`;
61
+ }
62
+
63
+ // Multiple keys - show abbreviated
64
+ const firstKey = keys[0]!;
65
+ return `{ ${firstKey}: ..., +${keys.length - 1} }`;
66
+ }
67
+
68
+ return String(value).slice(0, maxLength);
69
+ }
70
+
71
+ /**
72
+ * Format a path array for display, stripping the "root" prefix.
73
+ *
74
+ * @param path - Array of path segments (e.g., ["root", "settings", "name"])
75
+ * @returns Formatted path string (e.g., "settings.name")
76
+ */
77
+ export function formatPath(path: string[]): string {
78
+ // Filter out "root" prefix
79
+ const filtered = path.filter((segment) => segment !== "root");
80
+ if (filtered.length === 0) {
81
+ return "";
82
+ }
83
+ return filtered.join(".");
84
+ }
85
+
86
+ /**
87
+ * Format a path as a breadcrumb trail for nested navigation.
88
+ * Truncates from the left if too long.
89
+ *
90
+ * @param path - Array of path segments
91
+ * @param maxLength - Maximum total length (default 50)
92
+ * @returns Breadcrumb string (e.g., "settings → permissions → mint")
93
+ */
94
+ export function formatBreadcrumb(path: string[], maxLength = 50): string {
95
+ // Filter out "root" prefix
96
+ const filtered = path.filter((segment) => segment !== "root");
97
+ if (filtered.length === 0) {
98
+ return "";
99
+ }
100
+
101
+ const separator = " \u2192 "; // Unicode right arrow
102
+ const joined = filtered.join(separator);
103
+
104
+ if (joined.length <= maxLength) {
105
+ return joined;
106
+ }
107
+
108
+ // Truncate from left, keeping most recent segments
109
+ const ellipsis = "...";
110
+ let result = "";
111
+ for (let i = filtered.length - 1; i >= 0; i--) {
112
+ const segment = filtered[i]!;
113
+ const candidate = i === filtered.length - 1 ? segment : segment + separator + result;
114
+ if (candidate.length + ellipsis.length + separator.length > maxLength && i < filtered.length - 1) {
115
+ return ellipsis + separator + result;
116
+ }
117
+ result = candidate;
118
+ }
119
+
120
+ // Safety clamp: if we still exceeded maxLength (e.g., last segment alone is too long),
121
+ // fall back to just the ellipsis to honor the maxLength contract.
122
+ if (result.length > maxLength) {
123
+ return ellipsis;
124
+ }
125
+
126
+ return result;
127
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Utility functions for menu-based struct editing.
3
+ */
4
+
5
+ export {
6
+ formatValuePreview,
7
+ formatPath,
8
+ formatBreadcrumb,
9
+ } from "./formatting.js";
10
+
11
+ export {
12
+ countRequiredFields,
13
+ isFieldRequired,
14
+ buildFieldLabel,
15
+ getInitialFieldState,
16
+ allRequiredFieldsFilled,
17
+ } from "./field-utils.js";