slice-machine-ui 2.19.1 → 2.19.2-alpha.lg-import-slices.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 (46) hide show
  1. package/out/404.html +1 -1
  2. package/out/_next/static/Q_2lm2CqEzK8hMGWeR30R/_buildManifest.js +1 -0
  3. package/out/_next/static/chunks/130-e1a16d2f94fb2b64.js +1 -0
  4. package/out/_next/static/chunks/{429-aab52070cad2884b.js → 429-e5d7e39160de9f5e.js} +1 -1
  5. package/out/_next/static/chunks/489-d6580011169630a1.js +1 -0
  6. package/out/_next/static/chunks/585-c89bb2471e85b9f8.js +1 -0
  7. package/out/_next/static/chunks/928-ebbe58b08e1e70b1.js +1 -0
  8. package/out/_next/static/chunks/954-bedaaabf664584a0.js +1 -0
  9. package/out/_next/static/chunks/pages/{_app-664e26e8e0083aaa.js → _app-a8345a65a46d8112.js} +1 -1
  10. package/out/_next/static/chunks/pages/custom-types/{[customTypeId]-af9376721beb489e.js → [customTypeId]-97120b65616617fb.js} +1 -1
  11. package/out/_next/static/chunks/pages/page-types/{[pageTypeId]-a24665e91b882169.js → [pageTypeId]-b358358b5c2c1c43.js} +1 -1
  12. package/out/_next/static/chunks/pages/slices/[lib]/[sliceName]/[variation]/{simulator-faeb6d2f77d97096.js → simulator-8c70298caf51bed0.js} +1 -1
  13. package/out/_next/static/chunks/pages/slices-d5a2b0fcb7490565.js +1 -0
  14. package/out/changelog.html +1 -1
  15. package/out/changes.html +1 -1
  16. package/out/custom-types/[customTypeId].html +1 -1
  17. package/out/custom-types.html +1 -1
  18. package/out/index.html +1 -1
  19. package/out/labs.html +1 -1
  20. package/out/page-types/[pageTypeId].html +1 -1
  21. package/out/slices/[lib]/[sliceName]/[variation]/simulator.html +1 -1
  22. package/out/slices/[lib]/[sliceName]/[variation].html +1 -1
  23. package/out/slices.html +1 -1
  24. package/package.json +5 -4
  25. package/src/features/customTypes/customTypesBuilder/CreateSliceFromImageModal/CreateSliceFromImageModal.tsx +3 -36
  26. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/ImportSlicesFromLibraryModal.tsx +291 -0
  27. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/SliceCard.tsx +48 -0
  28. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/hooks/useImportSlicesFromGithub.ts +93 -0
  29. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/index.tsx +1 -0
  30. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/types.ts +28 -0
  31. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/utils/addSlices.ts +193 -0
  32. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/utils/github.ts +630 -0
  33. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/utils/mapWithConcurrency.ts +28 -0
  34. package/src/features/customTypes/customTypesBuilder/ImportSlicesFromLibraryModal/utils/sliceWithoutConflicts.ts +51 -0
  35. package/src/features/customTypes/customTypesBuilder/SliceZoneBlankSlate.tsx +11 -0
  36. package/src/features/customTypes/customTypesBuilder/shared/getSubmitButtonLabel.ts +12 -0
  37. package/src/features/customTypes/customTypesBuilder/shared/useExistingSlices.ts +26 -0
  38. package/src/features/customTypes/customTypesBuilder/sliceCreationOptions.tsx +14 -0
  39. package/src/legacy/lib/builders/CustomTypeBuilder/SliceZone/index.tsx +51 -0
  40. package/src/pages/slices.tsx +30 -0
  41. package/out/_next/static/chunks/422-c9192a1dbdd2ae0e.js +0 -1
  42. package/out/_next/static/chunks/489-ce3053e1d81ade83.js +0 -1
  43. package/out/_next/static/chunks/907-180eb33eefccc237.js +0 -1
  44. package/out/_next/static/chunks/pages/slices-81c1c3f1bcad60f4.js +0 -1
  45. package/out/_next/static/mWW0JPKbrqF9bfSpOlAsb/_buildManifest.js +0 -1
  46. /package/out/_next/static/{mWW0JPKbrqF9bfSpOlAsb → Q_2lm2CqEzK8hMGWeR30R}/_ssgManifest.js +0 -0
@@ -0,0 +1,291 @@
1
+ import {
2
+ Box,
3
+ Button,
4
+ Dialog,
5
+ DialogActionButton,
6
+ DialogActions,
7
+ DialogCancelButton,
8
+ DialogContent,
9
+ DialogDescription,
10
+ DialogHeader,
11
+ ScrollArea,
12
+ Text,
13
+ TextInput,
14
+ } from "@prismicio/editor-ui";
15
+ import { SharedSlice } from "@prismicio/types-internal/lib/customtypes";
16
+ import { useEffect, useRef, useState } from "react";
17
+ import { toast } from "react-toastify";
18
+
19
+ import { getState, telemetry } from "@/apiClient";
20
+ import { useOnboarding } from "@/features/onboarding/useOnboarding";
21
+ import { useAutoSync } from "@/features/sync/AutoSyncProvider";
22
+ import useSliceMachineActions from "@/modules/useSliceMachineActions";
23
+
24
+ import { getSubmitButtonLabel } from "../shared/getSubmitButtonLabel";
25
+ import { useExistingSlices } from "../shared/useExistingSlices";
26
+ import { useImportSlicesFromGithub } from "./hooks/useImportSlicesFromGithub";
27
+ import { SliceCard } from "./SliceCard";
28
+ import { NewSlice } from "./types";
29
+ import { addSlices } from "./utils/addSlices";
30
+ import { sliceWithoutConflicts } from "./utils/sliceWithoutConflicts";
31
+
32
+ interface ImportSlicesFromLibraryModalProps {
33
+ open: boolean;
34
+ location: "custom_type" | "page_type" | "slices";
35
+ onSuccess: (args: {
36
+ slices: {
37
+ model: SharedSlice;
38
+ langSmithUrl?: string;
39
+ }[];
40
+ library: string;
41
+ }) => void;
42
+ onClose: () => void;
43
+ }
44
+
45
+ export function ImportSlicesFromLibraryModal(
46
+ props: ImportSlicesFromLibraryModalProps,
47
+ ) {
48
+ const { open, location, onSuccess, onClose } = props;
49
+
50
+ const [isCreatingSlices, setIsCreatingSlices] = useState(false);
51
+ const [githubUrl, setGithubUrl] = useState("");
52
+ const [selectedSliceIds, setSelectedSliceIds] = useState<Set<string>>(
53
+ new Set(),
54
+ );
55
+
56
+ const { syncChanges } = useAutoSync();
57
+ const { createSliceSuccess, updateSliceMockSuccess } =
58
+ useSliceMachineActions();
59
+ const { completeStep } = useOnboarding();
60
+ const existingSlices = useExistingSlices({ open });
61
+ const { isLoadingSlices, handleImportFromGithub, slices, resetSlices } =
62
+ useImportSlicesFromGithub();
63
+
64
+ useEffect(() => {
65
+ if (slices.length === 0) return;
66
+
67
+ // Set all slices as selected by default
68
+ const allSliceIds = new Set<string>();
69
+ for (const slice of slices) {
70
+ allSliceIds.add(slice.model.id);
71
+ }
72
+ setSelectedSliceIds(allSliceIds);
73
+ }, [slices]);
74
+
75
+ /**
76
+ * Keeps track of the current instance id.
77
+ * When the modal is closed, the id is reset.
78
+ */
79
+ const id = useRef(crypto.randomUUID());
80
+
81
+ const onOpenChange = (open: boolean) => {
82
+ if (open || isCreatingSlices) return;
83
+ onClose();
84
+ id.current = crypto.randomUUID();
85
+ setGithubUrl("");
86
+ setSelectedSliceIds(new Set());
87
+ resetSlices();
88
+ };
89
+
90
+ const onSubmit = () => {
91
+ const newSlices = slices.reduce<NewSlice[]>((acc, slice) => {
92
+ if (selectedSliceIds.has(slice.model.id)) {
93
+ acc.push({
94
+ image: slice.image,
95
+ model: slice.model,
96
+ files: slice.files,
97
+ componentContents: slice.componentContents,
98
+ mocks: slice.mocks,
99
+ screenshots: slice.screenshots,
100
+ });
101
+ }
102
+ return acc;
103
+ }, []);
104
+ if (!newSlices.length) {
105
+ toast.error("Please select at least one slice to import");
106
+ return;
107
+ }
108
+
109
+ // Ensure ids and names are conflict-free against existing and newly-added slices
110
+ const conflictFreeSlices: NewSlice[] = [];
111
+ for (const s of newSlices) {
112
+ const adjustedModel = sliceWithoutConflicts({
113
+ existingSlices: existingSlices.current,
114
+ newSlices: conflictFreeSlices,
115
+ slice: s.model,
116
+ });
117
+ conflictFreeSlices.push({ ...s, model: adjustedModel });
118
+ }
119
+
120
+ const currentId = id.current;
121
+ setIsCreatingSlices(true);
122
+ addSlices(conflictFreeSlices)
123
+ .then(async ({ slices, library }) => {
124
+ if (currentId !== id.current) return;
125
+
126
+ // Wait a moment to ensure all file writes are complete
127
+ await new Promise((resolve) => setTimeout(resolve, 100));
128
+
129
+ const serverState = await getState();
130
+
131
+ // Ensure mocks are included in the libraries data before updating store
132
+ const librariesWithMocks = serverState.libraries.map((lib) => {
133
+ if (lib.name !== library) return lib;
134
+
135
+ return {
136
+ ...lib,
137
+ components: lib.components.map((component) => {
138
+ // Find the corresponding slice from newSlices to get its mocks
139
+ const importedSlice = conflictFreeSlices.find(
140
+ (s) => s.model.id === component.model.id,
141
+ );
142
+
143
+ // If mocks are already in component, use them; otherwise use imported mocks
144
+ const mocks =
145
+ component.mocks && component.mocks.length > 0
146
+ ? component.mocks
147
+ : importedSlice?.mocks;
148
+
149
+ return {
150
+ ...component,
151
+ mocks: mocks ?? component.mocks,
152
+ };
153
+ }),
154
+ };
155
+ });
156
+
157
+ createSliceSuccess(librariesWithMocks);
158
+
159
+ // Also update mocks individually to ensure they're in the store
160
+ for (const slice of newSlices) {
161
+ if (
162
+ slice.mocks &&
163
+ Array.isArray(slice.mocks) &&
164
+ slice.mocks.length > 0
165
+ ) {
166
+ updateSliceMockSuccess({
167
+ libraryID: library,
168
+ sliceID: slice.model.id,
169
+ mocks: slice.mocks,
170
+ });
171
+ }
172
+ }
173
+
174
+ syncChanges();
175
+
176
+ onSuccess({ slices, library });
177
+
178
+ setIsCreatingSlices(false);
179
+ id.current = crypto.randomUUID();
180
+ resetSlices();
181
+
182
+ void completeStep("createSlice");
183
+
184
+ for (const { model } of slices) {
185
+ void telemetry.track({
186
+ event: "slice:created",
187
+ id: model.id,
188
+ name: model.name,
189
+ library,
190
+ location,
191
+ mode: "import",
192
+ });
193
+ }
194
+ })
195
+ .catch(() => {
196
+ if (currentId !== id.current) return;
197
+ setIsCreatingSlices(false);
198
+ toast.error("An unexpected error happened while adding slices.");
199
+ });
200
+ };
201
+
202
+ const selectedSlices = slices.filter((slice) =>
203
+ selectedSliceIds.has(slice.model.id),
204
+ );
205
+
206
+ return (
207
+ <Dialog open={open} onOpenChange={onOpenChange}>
208
+ <DialogHeader title="Import slices from library" />
209
+ <DialogContent gap={0}>
210
+ <DialogDescription hidden>
211
+ Import slices from a github repository
212
+ </DialogDescription>
213
+ {slices.length === 0 ? (
214
+ <Box padding={16} height="100%" flexDirection="column" gap={16}>
215
+ <Box flexDirection="column" gap={8}>
216
+ <Box
217
+ display="flex"
218
+ flexDirection="column"
219
+ gap={8}
220
+ padding={16}
221
+ border
222
+ borderRadius={8}
223
+ >
224
+ <Text color="grey11">Import from GitHub</Text>
225
+ <TextInput
226
+ placeholder="https://github.com/username/repository"
227
+ value={githubUrl}
228
+ onValueChange={setGithubUrl}
229
+ />
230
+ <Button
231
+ onClick={() => handleImportFromGithub(githubUrl)}
232
+ disabled={!githubUrl.trim() || isLoadingSlices}
233
+ loading={isLoadingSlices}
234
+ color="purple"
235
+ >
236
+ {isLoadingSlices ? "Loading slices..." : "Import from GitHub"}
237
+ </Button>
238
+ </Box>
239
+ </Box>
240
+ </Box>
241
+ ) : (
242
+ <ScrollArea stableScrollbar={false}>
243
+ <Box
244
+ display="grid"
245
+ gridTemplateColumns="1fr 1fr 1fr"
246
+ gap={16}
247
+ padding={16}
248
+ >
249
+ {slices.map((slice) => {
250
+ return (
251
+ <SliceCard
252
+ model={slice.model}
253
+ thumbnailUrl={slice.thumbnailUrl}
254
+ key={slice.model.id}
255
+ selected={selectedSliceIds.has(slice.model.id)}
256
+ onSelectedChange={(selected) => {
257
+ if (selected) {
258
+ setSelectedSliceIds((prev) => {
259
+ const next = new Set(prev);
260
+ next.add(slice.model.id);
261
+ return next;
262
+ });
263
+ } else {
264
+ setSelectedSliceIds((prev) => {
265
+ const next = new Set(prev);
266
+ next.delete(slice.model.id);
267
+ return next;
268
+ });
269
+ }
270
+ }}
271
+ />
272
+ );
273
+ })}
274
+ </Box>
275
+ </ScrollArea>
276
+ )}
277
+
278
+ <DialogActions>
279
+ <DialogCancelButton disabled={isCreatingSlices} />
280
+ <DialogActionButton
281
+ disabled={selectedSlices.length === 0}
282
+ loading={isCreatingSlices}
283
+ onClick={onSubmit}
284
+ >
285
+ {getSubmitButtonLabel(location)} ({selectedSlices.length})
286
+ </DialogActionButton>
287
+ </DialogActions>
288
+ </DialogContent>
289
+ </Dialog>
290
+ );
291
+ }
@@ -0,0 +1,48 @@
1
+ import { Checkbox } from "@prismicio/editor-ui";
2
+ import { SharedSlice } from "@prismicio/types-internal/lib/customtypes";
3
+
4
+ import { Card, CardFooter, CardMedia } from "@/components/Card";
5
+
6
+ interface SliceCardProps {
7
+ thumbnailUrl?: string;
8
+ model: SharedSlice;
9
+ selected: boolean;
10
+ onSelectedChange: (selected: boolean) => void;
11
+ }
12
+
13
+ export function SliceCard(props: SliceCardProps) {
14
+ const { thumbnailUrl, model, selected = true, onSelectedChange } = props;
15
+
16
+ const handleClick = () => {
17
+ onSelectedChange(!selected);
18
+ };
19
+
20
+ const cardContent = (
21
+ <>
22
+ {thumbnailUrl !== undefined && thumbnailUrl ? (
23
+ <CardMedia src={thumbnailUrl} />
24
+ ) : (
25
+ <CardMedia component="div" />
26
+ )}
27
+ <CardFooter
28
+ title={model.name}
29
+ action={
30
+ <div onClick={(event) => event.stopPropagation()}>
31
+ <Checkbox checked={selected} onCheckedChange={onSelectedChange} />
32
+ </div>
33
+ }
34
+ />
35
+ </>
36
+ );
37
+
38
+ return (
39
+ <Card
40
+ interactive={true}
41
+ onClick={handleClick}
42
+ checked={selected}
43
+ size="small"
44
+ >
45
+ {cardContent}
46
+ </Card>
47
+ );
48
+ }
@@ -0,0 +1,93 @@
1
+ import { useState } from "react";
2
+ import { toast } from "react-toastify";
3
+
4
+ import { SliceImport } from "../types";
5
+ import {
6
+ fetchSlicesFromLibraries,
7
+ getDefaultBranch,
8
+ getSliceLibraries,
9
+ parseGithubUrl,
10
+ } from "../utils/github";
11
+
12
+ export function useImportSlicesFromGithub() {
13
+ const [isLoadingSlices, setIsLoadingSlices] = useState(false);
14
+ const [slices, setSlices] = useState<SliceImport[]>([]);
15
+
16
+ const resetSlices = () => {
17
+ setSlices([]);
18
+ setIsLoadingSlices(false);
19
+ };
20
+
21
+ const handleImportFromGithub = (githubUrl: string) => {
22
+ void (async () => {
23
+ try {
24
+ setIsLoadingSlices(true);
25
+
26
+ const { owner, repo } = parseGithubUrl(githubUrl);
27
+ if (!owner || !repo) {
28
+ toast.error("Invalid GitHub URL format");
29
+ setIsLoadingSlices(false);
30
+ return;
31
+ }
32
+
33
+ const branch = await getDefaultBranch({ owner, repo });
34
+
35
+ let libraries: string[] | undefined;
36
+
37
+ try {
38
+ libraries = await getSliceLibraries({ owner, repo, branch });
39
+ } catch (error) {
40
+ console.error("Failed to fetch slicemachine.config.json:", error);
41
+ toast.error(
42
+ `Failed to fetch slicemachine.config.json: ${
43
+ error instanceof Error ? error.message : "Unknown error"
44
+ }`,
45
+ );
46
+ setIsLoadingSlices(false);
47
+ return;
48
+ }
49
+
50
+ if (libraries.length === 0) {
51
+ console.warn("No libraries were found in the SM config.");
52
+ setIsLoadingSlices(false);
53
+ toast.error("No libraries were found in the SM config.");
54
+ return;
55
+ }
56
+
57
+ const fetchedSlices = await fetchSlicesFromLibraries({
58
+ owner,
59
+ repo,
60
+ branch,
61
+ libraries,
62
+ });
63
+
64
+ if (fetchedSlices.length === 0) {
65
+ toast.error("Error fetching slices from the repository");
66
+ setIsLoadingSlices(false);
67
+ return;
68
+ }
69
+
70
+ setSlices(fetchedSlices);
71
+ setIsLoadingSlices(false);
72
+ toast.success(
73
+ `Found ${fetchedSlices.length} slice(s) from ${libraries.length} library/libraries`,
74
+ );
75
+ } catch (error) {
76
+ console.error("Error importing from GitHub:", error);
77
+ toast.error(
78
+ `Error importing from GitHub: ${
79
+ error instanceof Error ? error.message : "Unknown error"
80
+ }`,
81
+ );
82
+ setIsLoadingSlices(false);
83
+ }
84
+ })();
85
+ };
86
+
87
+ return {
88
+ isLoadingSlices,
89
+ slices,
90
+ resetSlices,
91
+ handleImportFromGithub,
92
+ };
93
+ }
@@ -0,0 +1 @@
1
+ export { ImportSlicesFromLibraryModal } from "./ImportSlicesFromLibraryModal";
@@ -0,0 +1,28 @@
1
+ import { SharedSliceContent } from "@prismicio/types-internal/lib/content";
2
+ import { SharedSlice } from "@prismicio/types-internal/lib/customtypes";
3
+
4
+ export type SliceImport = {
5
+ image: File;
6
+ model: SharedSlice;
7
+ thumbnailUrl?: string;
8
+ files?: SliceFile[];
9
+ componentContents?: string;
10
+ mocks?: SharedSliceContent[];
11
+ screenshots?: Record<string, File>;
12
+ };
13
+
14
+ export type SliceFile = {
15
+ path: string;
16
+ contents: string | ArrayBuffer;
17
+ isBinary: boolean;
18
+ };
19
+
20
+ export type NewSlice = {
21
+ image: File;
22
+ model: SharedSlice;
23
+ langSmithUrl?: string;
24
+ files?: SliceFile[];
25
+ componentContents?: string;
26
+ mocks?: SharedSliceContent[];
27
+ screenshots?: Record<string, File>;
28
+ };
@@ -0,0 +1,193 @@
1
+ import { managerClient } from "@/managerClient";
2
+
3
+ import { NewSlice, SliceFile } from "../types";
4
+ import { mapWithConcurrency } from "./mapWithConcurrency";
5
+
6
+ export async function addSlices(newSlices: NewSlice[]) {
7
+ // use the first library
8
+ const { libraries = [] } =
9
+ await managerClient.project.getSliceMachineConfig();
10
+ const library = libraries[0];
11
+ if (!library) {
12
+ throw new Error("No library found in the config.");
13
+ }
14
+
15
+ // Create slices with bounded concurrency
16
+ await mapWithConcurrency(newSlices, 3, async (slice: NewSlice) => {
17
+ const { errors } = await managerClient.slices.createSlice({
18
+ libraryID: library,
19
+ model: slice.model,
20
+ componentContents: slice.componentContents,
21
+ });
22
+ if (errors.length) {
23
+ throw new Error(`Failed to create slice ${slice.model.id}.`);
24
+ }
25
+ });
26
+
27
+ // Update mocks and screenshots, and write additional files
28
+ const slices = await mapWithConcurrency(
29
+ newSlices,
30
+ 3,
31
+ async (slice: NewSlice) => {
32
+ const { model, image, langSmithUrl, mocks, files, screenshots } = slice;
33
+
34
+ // Update mocks if available
35
+ if (mocks && Array.isArray(mocks) && mocks.length > 0) {
36
+ const { errors: mocksErrors } =
37
+ await managerClient.slices.updateSliceMocks({
38
+ libraryID: library,
39
+ sliceID: model.id,
40
+ mocks,
41
+ });
42
+ if (mocksErrors.length) {
43
+ console.warn(
44
+ `Failed to update mocks for slice ${model.id}:`,
45
+ mocksErrors,
46
+ );
47
+ }
48
+ }
49
+
50
+ // Update screenshots for all variations
51
+ if (screenshots && Object.keys(screenshots).length > 0) {
52
+ await Promise.all(
53
+ Object.entries(screenshots).map(
54
+ async ([variationID, screenshotFile]) => {
55
+ if (screenshotFile.size > 0) {
56
+ await managerClient.slices.updateSliceScreenshot({
57
+ libraryID: library,
58
+ sliceID: model.id,
59
+ variationID,
60
+ data: screenshotFile,
61
+ });
62
+ }
63
+ },
64
+ ),
65
+ );
66
+ } else if (
67
+ image.size > 0 &&
68
+ model.variations !== undefined &&
69
+ model.variations.length > 0
70
+ ) {
71
+ // Fallback to using the first image if no screenshots were provided
72
+ await managerClient.slices.updateSliceScreenshot({
73
+ libraryID: library,
74
+ sliceID: model.id,
75
+ variationID: model.variations[0].id,
76
+ data: image,
77
+ });
78
+ }
79
+
80
+ // Write additional files (CSS, other assets, etc.)
81
+ console.log(
82
+ `About to write files for slice ${model.id}:`,
83
+ files
84
+ ? `${files.length} file(s) - ${files
85
+ .map((f: SliceFile) => f.path)
86
+ .join(", ")}`
87
+ : "no files",
88
+ );
89
+ if (files && files.length > 0) {
90
+ await writeSliceFiles({
91
+ libraryID: library,
92
+ sliceID: model.id,
93
+ files,
94
+ });
95
+ } else {
96
+ console.warn(`No files to write for slice ${model.id}. Files:`, files);
97
+ }
98
+
99
+ return { model, langSmithUrl };
100
+ },
101
+ );
102
+
103
+ return { library, slices };
104
+ }
105
+
106
+ /**
107
+ * Writes additional slice files to the filesystem using the manager's plugin runner
108
+ * Uses the manager client's RPC interface to write files
109
+ */
110
+ async function writeSliceFiles(args: {
111
+ libraryID: string;
112
+ sliceID: string;
113
+ files: SliceFile[];
114
+ }): Promise<void> {
115
+ const { libraryID, sliceID, files } = args;
116
+
117
+ if (files.length === 0) {
118
+ return;
119
+ }
120
+
121
+ // Filter out files that are already handled by other methods
122
+ // Note: We still write ALL files, but skip ones that are handled by createSlice/updateSliceMocks/updateSliceScreenshot
123
+ // This includes component files in subdirectories, CSS files, assets, etc.
124
+ const filesToWrite = files.filter(
125
+ (file) =>
126
+ // Skip mocks.json (handled by updateSliceMocks)
127
+ file.path !== "mocks.json" &&
128
+ // Skip screenshots (handled by updateSliceScreenshot)
129
+ !file.path.startsWith("screenshot-") &&
130
+ // Skip the main index component file (handled by createSlice with componentContents)
131
+ // But allow component files in subdirectories (e.g., components/Button.tsx)
132
+ !file.path.match(/^index\.(tsx?|jsx?|vue|svelte)$/),
133
+ );
134
+
135
+ console.log(
136
+ `Writing ${filesToWrite.length} additional file(s) for slice ${sliceID}:`,
137
+ filesToWrite.map((f) => f.path),
138
+ );
139
+
140
+ if (filesToWrite.length === 0) {
141
+ return;
142
+ }
143
+
144
+ try {
145
+ // Convert ArrayBuffer to base64 string for binary files to send via RPC
146
+ const filesForRPC = filesToWrite.map((file) => {
147
+ if (file.isBinary && file.contents instanceof ArrayBuffer) {
148
+ // Convert ArrayBuffer to base64
149
+ const bytes = new Uint8Array(file.contents);
150
+ const binary = bytes.reduce(
151
+ (acc, byte) => acc + String.fromCharCode(byte),
152
+ "",
153
+ );
154
+ return {
155
+ path: file.path,
156
+ contents: btoa(binary),
157
+ isBinary: true,
158
+ };
159
+ } else if (typeof file.contents === "string") {
160
+ return {
161
+ path: file.path,
162
+ contents: file.contents,
163
+ isBinary: false,
164
+ };
165
+ } else {
166
+ throw new Error(`Unexpected file contents type for ${file.path}`);
167
+ }
168
+ });
169
+
170
+ const result = await managerClient.slices.writeSliceFiles({
171
+ libraryID,
172
+ sliceID,
173
+ files: filesForRPC,
174
+ });
175
+
176
+ if (result.errors.length > 0) {
177
+ console.error(
178
+ `Errors writing files for slice ${sliceID}:`,
179
+ result.errors.map((e: { message?: string }) => e.message ?? String(e)),
180
+ );
181
+ } else {
182
+ console.log(
183
+ `Successfully wrote ${filesToWrite.length} file(s) for slice ${sliceID}`,
184
+ );
185
+ }
186
+ } catch (error) {
187
+ console.error(
188
+ `Error writing files for slice ${sliceID}:`,
189
+ error instanceof Error ? error.message : String(error),
190
+ );
191
+ // Don't throw - allow slice creation to succeed even if some files fail
192
+ }
193
+ }