@mcp-web/decompose-zod-schema 0.1.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.
- package/LICENSE +201 -0
- package/README.md +358 -0
- package/dist/apply.d.ts +2 -0
- package/dist/apply.d.ts.map +1 -0
- package/dist/apply.js +65 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +164 -0
- package/dist/decompose.d.ts +41 -0
- package/dist/decompose.d.ts.map +1 -0
- package/dist/decompose.js +383 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/plan-builder.d.ts +81 -0
- package/dist/plan-builder.d.ts.map +1 -0
- package/dist/plan-builder.js +109 -0
- package/dist/schemas.d.ts +14 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +22 -0
- package/dist/split-suggestions.d.ts +42 -0
- package/dist/split-suggestions.d.ts.map +1 -0
- package/dist/split-suggestions.js +179 -0
- package/dist/types.d.ts +93 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +20 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +161 -0
- package/dist/validate.d.ts +9 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/validate.js +134 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Fritz Lekschas
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
# Schema Decomposition for AI Tools
|
|
2
|
+
|
|
3
|
+
Large schemas create two fundamental challenges when working with AI systems:
|
|
4
|
+
|
|
5
|
+
## 1. Descriptive Complexity
|
|
6
|
+
When schemas have too many properties, AI might struggle to understand and work
|
|
7
|
+
with all concepts simultaneously. Complex schemas can exceed context limits and
|
|
8
|
+
reduce AI's ability to generate accurate, focused responses.
|
|
9
|
+
|
|
10
|
+
**Solution: Schema Decomposition**
|
|
11
|
+
- Split large objects into semantically-coherent sub-schemas
|
|
12
|
+
- This results in focused schemas that handle specific domains of properties
|
|
13
|
+
- Each sub-schema can be processed independently, improving AI accuracy and efficiency
|
|
14
|
+
- Perfect for breaking down complex forms, configuration objects, or data models
|
|
15
|
+
|
|
16
|
+
## 2. Generative Complexity
|
|
17
|
+
When schemas contain unbounded collections (arrays, records, maps), the AI might need to manage many items at once, which can lead to errors and inefficiency. Generating or updating large collections can overwhelm AI systems and result in incomplete or incorrect data.
|
|
18
|
+
|
|
19
|
+
**Solution: Value Generation Decomposition**
|
|
20
|
+
- Transform collections into single-item + indexing operations
|
|
21
|
+
- AI generates/updates one item at a time with precise targeting
|
|
22
|
+
- Supports both arrays (`items[]`) and records/maps (`configs{}`)
|
|
23
|
+
- Enables incremental updates to large datasets without losing context
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
This utility provides both types of decomposition through a flexible, type-safe API that works seamlessly with Zod schemas and maintains full TypeScript support.
|
|
28
|
+
|
|
29
|
+
## Features
|
|
30
|
+
|
|
31
|
+
- **Manual Decomposition**: Use split plans to precisely control how schemas are decomposed
|
|
32
|
+
- **Automatic Suggestions**: Size-based algorithms to suggest optimal decomposition plans
|
|
33
|
+
- **Enum Splitting**: Automatically splits large enums into smaller chunks with flexible notation
|
|
34
|
+
- **Array Decomposition**: Transform arrays into single-item schemas with `items[]` notation
|
|
35
|
+
- **Record Decomposition**: Transform records/maps into key-value pairs with `configs{}` notation
|
|
36
|
+
- **Plan Validation**: Validate split plans against schemas before decomposition
|
|
37
|
+
- **Partial Updates**: Apply updates from decomposed schemas to complete objects
|
|
38
|
+
- **Extensible Strategy System**: Plugin architecture for custom decomposition algorithms
|
|
39
|
+
- **Type Safety**: Maintains full TypeScript type safety throughout
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
### Automatic Decomposition (Size-based)
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { decomposeSchema, applyPartialUpdate } from '@your-company/decompose-zod-schema';
|
|
47
|
+
import { z } from 'zod';
|
|
48
|
+
|
|
49
|
+
// Define a complex schema
|
|
50
|
+
const userSchema = z.object({
|
|
51
|
+
user: z.object({
|
|
52
|
+
id: z.string().uuid(),
|
|
53
|
+
name: z.string(),
|
|
54
|
+
email: z.string().email(),
|
|
55
|
+
}),
|
|
56
|
+
profile: z.object({
|
|
57
|
+
bio: z.string(),
|
|
58
|
+
avatar: z.string().url().optional(),
|
|
59
|
+
}),
|
|
60
|
+
preferences: z.object({
|
|
61
|
+
theme: z.enum(['light', 'dark', 'auto']),
|
|
62
|
+
language: z.enum(['en', 'es', 'fr', 'de']),
|
|
63
|
+
}),
|
|
64
|
+
// Large enum for testing
|
|
65
|
+
category: z.enum(Array.from({ length: 200 }, (_, i) => `cat-${i}`) as [string, ...string[]]),
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// Automatic decomposition with size constraints
|
|
69
|
+
const decomposed = decomposeSchema(userSchema, {
|
|
70
|
+
maxTokensPerSchema: 1500,
|
|
71
|
+
maxOptionsPerEnum: 50,
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
console.log(decomposed);
|
|
75
|
+
// [
|
|
76
|
+
// { name: "user", schema: z.object({...}), targetPaths: ["user.id", "user.name", "user.email"] },
|
|
77
|
+
// { name: "profile", schema: z.object({...}), targetPaths: ["profile.bio", "profile.avatar"] },
|
|
78
|
+
// { name: "preferences", schema: z.object({...}), targetPaths: ["preferences.theme", "preferences.language"] },
|
|
79
|
+
// { name: "category-1", schema: z.object({...}), targetPaths: ["category[0:50]"] },
|
|
80
|
+
// { name: "category-2", schema: z.object({...}), targetPaths: ["category[50:100]"] },
|
|
81
|
+
// // ... more category chunks
|
|
82
|
+
// ]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Manual Decomposition (Split Plans)
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
import { decomposeSchema, PlanBuilder } from '@your-company/decompose-zod-schema';
|
|
89
|
+
|
|
90
|
+
// Simple static plan
|
|
91
|
+
const plan = [
|
|
92
|
+
'user',
|
|
93
|
+
'profile',
|
|
94
|
+
'preferences',
|
|
95
|
+
'category[50]', // Split category enum into chunks of 50
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
const decomposed = decomposeSchema(userSchema, plan);
|
|
99
|
+
|
|
100
|
+
// Using the plan builder for more complex scenarios
|
|
101
|
+
const builderPlan = new PlanBuilder()
|
|
102
|
+
.addSplit('user')
|
|
103
|
+
.addSplit('profile')
|
|
104
|
+
.addConditionalEnumSplit('preferences.language', 10, userSchema)
|
|
105
|
+
.addEnumSplit('category', 50)
|
|
106
|
+
.build();
|
|
107
|
+
|
|
108
|
+
const decomposedFromBuilder = decomposeSchema(userSchema, builderPlan);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Array and Record Decomposition
|
|
112
|
+
|
|
113
|
+
Transform collections into manageable single-item operations:
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
import { decomposeSchema, applyPartialUpdate } from '@your-company/decompose-zod-schema';
|
|
117
|
+
import { z } from 'zod';
|
|
118
|
+
|
|
119
|
+
// Schema with arrays and records
|
|
120
|
+
const dataSchema = z.object({
|
|
121
|
+
users: z.array(z.object({
|
|
122
|
+
name: z.string(),
|
|
123
|
+
email: z.string(),
|
|
124
|
+
roles: z.array(z.string())
|
|
125
|
+
})),
|
|
126
|
+
settings: z.record(z.string(), z.object({
|
|
127
|
+
enabled: z.boolean(),
|
|
128
|
+
value: z.string()
|
|
129
|
+
})),
|
|
130
|
+
metadata: z.string()
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
// Decompose collections into single-item schemas
|
|
134
|
+
const plan = [
|
|
135
|
+
'metadata', // Regular property
|
|
136
|
+
'users[]', // Array decomposition: z.array(T) → z.object({ index: number, value: T })
|
|
137
|
+
'settings{}' // Record decomposition: z.record(K, V) → z.object({ key: K, value: V })
|
|
138
|
+
];
|
|
139
|
+
|
|
140
|
+
const decomposed = decomposeSchema(dataSchema, plan);
|
|
141
|
+
console.log(decomposed);
|
|
142
|
+
// [
|
|
143
|
+
// { name: "metadata", schema: z.object({ metadata: z.string() }), targetPaths: ["metadata"] },
|
|
144
|
+
// { name: "users-item", schema: z.object({ index: z.number(), value: UserSchema }), targetPaths: ["users[]"] },
|
|
145
|
+
// { name: "settings-entry", schema: z.object({ key: z.string(), value: SettingSchema }), targetPaths: ["settings{}"] }
|
|
146
|
+
// ]
|
|
147
|
+
|
|
148
|
+
// Apply single-item updates
|
|
149
|
+
const currentData = {
|
|
150
|
+
users: [
|
|
151
|
+
{ name: 'Alice', email: 'alice@example.com', roles: ['user'] },
|
|
152
|
+
{ name: 'Bob', email: 'bob@example.com', roles: ['admin'] }
|
|
153
|
+
],
|
|
154
|
+
settings: {
|
|
155
|
+
theme: { enabled: true, value: 'dark' },
|
|
156
|
+
debug: { enabled: false, value: 'off' }
|
|
157
|
+
},
|
|
158
|
+
metadata: 'User Management System'
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// Update a specific array element
|
|
162
|
+
const usersSchema = decomposed.find(s => s.name === 'users-item');
|
|
163
|
+
const arrayUpdate = {
|
|
164
|
+
index: 0,
|
|
165
|
+
value: { name: 'Alice Updated', email: 'alice.new@example.com', roles: ['user', 'moderator'] }
|
|
166
|
+
};
|
|
167
|
+
const updatedData = applyPartialUpdate(currentData, usersSchema.targetPaths, arrayUpdate);
|
|
168
|
+
|
|
169
|
+
// Update a specific record entry
|
|
170
|
+
const settingsSchema = decomposed.find(s => s.name === 'settings-entry');
|
|
171
|
+
const recordUpdate = {
|
|
172
|
+
key: 'debug',
|
|
173
|
+
value: { enabled: true, value: 'verbose' }
|
|
174
|
+
};
|
|
175
|
+
const finalData = applyPartialUpdate(updatedData, settingsSchema.targetPaths, recordUpdate);
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Split Plan Validation
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
import { validatePlan } from '@your-company/decompose-zod-schema';
|
|
182
|
+
|
|
183
|
+
const plan = ['user', 'profile', 'nonexistent.path', 'category[1000]'];
|
|
184
|
+
const errors = validatePlan(plan, userSchema);
|
|
185
|
+
|
|
186
|
+
if (errors.length > 0) {
|
|
187
|
+
console.log('Plan validation errors:', errors);
|
|
188
|
+
// ["Path 'nonexistent.path' does not exist in schema", "Invalid slice range..."]
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Advanced Strategy System
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import {
|
|
196
|
+
suggestWithStrategy,
|
|
197
|
+
SuggestionStrategyRegistry,
|
|
198
|
+
SemanticSuggestionStrategy
|
|
199
|
+
} from '@your-company/decompose-zod-schema';
|
|
200
|
+
|
|
201
|
+
// Use different suggestion strategies
|
|
202
|
+
const sizeBasedPlan = suggestWithStrategy('size-based', userSchema, {
|
|
203
|
+
maxTokensPerSchema: 1500,
|
|
204
|
+
maxOptionsPerEnum: 50
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Register custom strategies
|
|
208
|
+
const registry = new SuggestionStrategyRegistry();
|
|
209
|
+
registry.register(new SemanticSuggestionStrategy());
|
|
210
|
+
|
|
211
|
+
const semanticPlan = registry.suggest('semantic', userSchema, {});
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Partial Updates
|
|
215
|
+
|
|
216
|
+
```typescript
|
|
217
|
+
const currentUser = {
|
|
218
|
+
user: { id: '123', name: 'John', email: 'john@example.com' },
|
|
219
|
+
profile: { bio: 'Developer', avatar: 'https://example.com/avatar.jpg' },
|
|
220
|
+
preferences: { theme: 'light', language: 'en' },
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// Apply a partial update for just the user information
|
|
224
|
+
const updatedUser = applyPartialUpdate(
|
|
225
|
+
currentUser,
|
|
226
|
+
['user.id', 'user.name', 'user.email'],
|
|
227
|
+
{ id: '456', name: 'Jane', email: 'jane@example.com' }
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
console.log(updatedUser);
|
|
231
|
+
// {
|
|
232
|
+
// user: { id: '456', name: 'Jane', email: 'jane@example.com' },
|
|
233
|
+
// profile: { bio: 'Developer', avatar: 'https://example.com/avatar.jpg' }, // unchanged
|
|
234
|
+
// preferences: { theme: 'light', language: 'en' } // unchanged
|
|
235
|
+
// }
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Command Line Interface
|
|
239
|
+
|
|
240
|
+
A Node.js CLI is provided for testing and analyzing schema decomposition:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
# Run tests
|
|
244
|
+
npm test
|
|
245
|
+
|
|
246
|
+
# Analyze a schema
|
|
247
|
+
npm run example
|
|
248
|
+
|
|
249
|
+
# Custom analysis
|
|
250
|
+
node decompose-cli.js -i schema.ts -s mySchema -t 1000 -v
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### CLI Options
|
|
254
|
+
|
|
255
|
+
- `-i, --input <file>`: Input TypeScript file containing schema
|
|
256
|
+
- `-s, --schema <name>`: Name of the schema variable to decompose
|
|
257
|
+
- `-o, --output <file>`: Output JSON file for results
|
|
258
|
+
- `-t, --tokens <number>`: Maximum tokens per decomposed schema (default: 2000)
|
|
259
|
+
- `-e, --enum-size <number>`: Maximum enum size before splitting (default: 200)
|
|
260
|
+
- `-v, --verbose`: Verbose output
|
|
261
|
+
- `-h, --help`: Show help
|
|
262
|
+
|
|
263
|
+
## Testing
|
|
264
|
+
|
|
265
|
+
Comprehensive tests are provided using Node.js test frameworks:
|
|
266
|
+
|
|
267
|
+
```bash
|
|
268
|
+
cd packages/decompose-zod-schema
|
|
269
|
+
npm test
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Tests cover:
|
|
273
|
+
- Basic schema decomposition
|
|
274
|
+
- Nested object handling
|
|
275
|
+
- Large enum splitting
|
|
276
|
+
- Partial update functionality
|
|
277
|
+
- Round-trip validation (ensuring decomposed updates maintain schema validity)
|
|
278
|
+
|
|
279
|
+
## Implementation Details
|
|
280
|
+
|
|
281
|
+
### Architecture Overview
|
|
282
|
+
|
|
283
|
+
The library is structured into distinct modules for maximum flexibility:
|
|
284
|
+
|
|
285
|
+
1. **Types** (`types.ts`): Core type definitions including `SplitPlan`, `DecomposedSchema`, and strategy interfaces
|
|
286
|
+
2. **Utils** (`utils.ts`): Internal utility functions for path manipulation, schema extraction, and validation
|
|
287
|
+
3. **Manual Decompose** (`manual-decompose.ts`): Core decomposition logic using explicit split plans
|
|
288
|
+
4. **Decompose** (`decompose.ts`): Main entry point that delegates to manual decomposition
|
|
289
|
+
5. **Split Suggestions** (`split-suggestions.ts`): Strategy system for automatic plan generation
|
|
290
|
+
6. **Index** (`index.ts`): Public API with convenience wrapper function
|
|
291
|
+
|
|
292
|
+
### Split Plan System
|
|
293
|
+
|
|
294
|
+
Split plans use a simple string-based notation:
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
type SplitPlan = Array<
|
|
298
|
+
| string // Simple path: 'user' or 'profile.bio'
|
|
299
|
+
| `${string}[${number}]` // Chunk notation: 'category[50]'
|
|
300
|
+
| `${string}[${number}:${number}]` // Slice notation: 'category[0:50]'
|
|
301
|
+
>;
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Examples:
|
|
305
|
+
- `'user'` - Extract the entire 'user' object
|
|
306
|
+
- `'profile.bio'` - Extract just the bio field from profile
|
|
307
|
+
- `'category[50]'` - Split category enum into chunks of 50 items each
|
|
308
|
+
- `'category[0:50]'` - Extract specific slice from category enum
|
|
309
|
+
|
|
310
|
+
### Strategy Pattern for Suggestions
|
|
311
|
+
|
|
312
|
+
The suggestion system uses a plugin architecture:
|
|
313
|
+
|
|
314
|
+
```typescript
|
|
315
|
+
interface SuggestionStrategy {
|
|
316
|
+
name: string;
|
|
317
|
+
suggest(schema: ZodObject<Record<string, ZodType>>, options?: unknown): SplitPlan;
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Built-in strategies:
|
|
322
|
+
- **Size-based**: Groups schemas by token count limits and enum size constraints
|
|
323
|
+
- **Semantic**: (Future) Groups by property name patterns and domain semantics
|
|
324
|
+
|
|
325
|
+
### Enum Handling
|
|
326
|
+
|
|
327
|
+
Enums support multiple splitting approaches:
|
|
328
|
+
- **Even chunking**: Distributes enum options evenly across chunks
|
|
329
|
+
- **Size-based chunking**: Creates chunks with maximum size limits
|
|
330
|
+
- **Explicit slicing**: Allows precise control over enum ranges
|
|
331
|
+
|
|
332
|
+
```typescript
|
|
333
|
+
// Original enum
|
|
334
|
+
z.enum(['opt1', 'opt2', ..., 'opt100'])
|
|
335
|
+
|
|
336
|
+
// Chunked with bracket notation
|
|
337
|
+
'category[25]' → [
|
|
338
|
+
'category[0:25]', // opts 1-25
|
|
339
|
+
'category[25:50]', // opts 26-50
|
|
340
|
+
'category[50:75]', // opts 51-75
|
|
341
|
+
'category[75:100]' // opts 76-100
|
|
342
|
+
]
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
## TypeScript Support
|
|
346
|
+
|
|
347
|
+
All types are properly defined with generic constraints:
|
|
348
|
+
- `DecomposedSchema`: Represents a decomposed schema with metadata
|
|
349
|
+
- `DecompositionOptions`: Configuration options for decomposition
|
|
350
|
+
- Full type inference for schema shapes and validation results
|
|
351
|
+
|
|
352
|
+
## Error Handling
|
|
353
|
+
|
|
354
|
+
The utility provides comprehensive error handling:
|
|
355
|
+
- Schema validation errors during decomposition
|
|
356
|
+
- Invalid partial update attempts
|
|
357
|
+
- Type mismatches and constraint violations
|
|
358
|
+
- Detailed error messages for debugging
|
package/dist/apply.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../src/apply.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,kBAAkB,GAC7B,cAAc,OAAO,EACrB,aAAa,MAAM,EAAE,EACrB,eAAe,OAAO,YAqEvB,CAAC"}
|
package/dist/apply.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { produce } from 'immer';
|
|
2
|
+
import { parseEnumSplit, setNestedValue } from './utils.js';
|
|
3
|
+
// Helper to get nested value
|
|
4
|
+
const get = (obj, path) => {
|
|
5
|
+
const keys = path.split('.');
|
|
6
|
+
let current = obj;
|
|
7
|
+
for (const key of keys) {
|
|
8
|
+
if (current == null)
|
|
9
|
+
return undefined;
|
|
10
|
+
current = current[key];
|
|
11
|
+
}
|
|
12
|
+
return current;
|
|
13
|
+
};
|
|
14
|
+
export const applyPartialUpdate = (currentState, targetPaths, partialUpdate) => {
|
|
15
|
+
return produce(currentState, (draft) => {
|
|
16
|
+
// Check if this is an array or record split update
|
|
17
|
+
const firstTargetPath = targetPaths[0];
|
|
18
|
+
const parsed = parseEnumSplit(firstTargetPath);
|
|
19
|
+
if (parsed.isArraySplit) {
|
|
20
|
+
// Handle array split update: partialUpdate should be { index: number, value: T }
|
|
21
|
+
const { index, value } = partialUpdate;
|
|
22
|
+
const arrayPath = parsed.path;
|
|
23
|
+
const arrayRef = get(draft, arrayPath);
|
|
24
|
+
if (!arrayRef || !Array.isArray(arrayRef)) {
|
|
25
|
+
console.warn(`Array not found at path: ${arrayPath}`);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (index < 0 || index >= arrayRef.length) {
|
|
29
|
+
console.warn(`Index ${index} out of bounds for array at ${arrayPath} (length: ${arrayRef.length})`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
// Update the array element
|
|
33
|
+
Object.assign(arrayRef[index], value);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (parsed.isRecordSplit) {
|
|
37
|
+
// Handle record split update: partialUpdate should be { key: K, value: V }
|
|
38
|
+
const { key, value } = partialUpdate;
|
|
39
|
+
const recordPath = parsed.path;
|
|
40
|
+
const recordRef = get(draft, recordPath);
|
|
41
|
+
if (!recordRef || typeof recordRef !== 'object') {
|
|
42
|
+
console.warn(`Record not found at path: ${recordPath}`);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// Update the record entry
|
|
46
|
+
recordRef[key] = value;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
// Handle regular property updates
|
|
50
|
+
Object.entries(partialUpdate).forEach(([key, value]) => {
|
|
51
|
+
// Find matching target path
|
|
52
|
+
const targetPath = targetPaths.find((path) => {
|
|
53
|
+
const parsedPath = parseEnumSplit(path);
|
|
54
|
+
// Exact match for leaf property
|
|
55
|
+
if (parsedPath.path.endsWith(`.${key}`) || parsedPath.path === key)
|
|
56
|
+
return true;
|
|
57
|
+
return false;
|
|
58
|
+
});
|
|
59
|
+
if (targetPath) {
|
|
60
|
+
const parsedPath = parseEnumSplit(targetPath);
|
|
61
|
+
setNestedValue(draft, parsedPath.path, value);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
};
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|