@slicemachine/manager 0.25.6 → 0.25.7-alpha.jp-figma-to-prismic.2

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.
@@ -23,6 +23,7 @@ import {
23
23
  HookError,
24
24
  } from "@slicemachine/plugin-kit";
25
25
  import { z } from "zod";
26
+ import { query as queryClaude } from "@anthropic-ai/claude-agent-sdk";
26
27
 
27
28
  import { DecodeError } from "../../lib/DecodeError";
28
29
  import { assertPluginsInitialized } from "../../lib/assertPluginsInitialized";
@@ -33,6 +34,11 @@ import { OnlyHookErrors } from "../../types";
33
34
  import { API_ENDPOINTS } from "../../constants/API_ENDPOINTS";
34
35
  import { SLICE_MACHINE_USER_AGENT } from "../../constants/SLICE_MACHINE_USER_AGENT";
35
36
  import { UnauthorizedError } from "../../errors";
37
+ import { mkdtemp, readFile, rename, rm, writeFile } from "fs/promises";
38
+ import { tmpdir } from "os";
39
+ import path from "path";
40
+ import { randomUUID } from "crypto";
41
+ import { existsSync } from "fs";
36
42
 
37
43
  import { BaseManager } from "../BaseManager";
38
44
  import { CustomTypeFormat } from "./types";
@@ -533,37 +539,329 @@ export class CustomTypesManager extends BaseManager {
533
539
  return await client.getAllCustomTypes();
534
540
  }
535
541
 
536
- async inferSlice({
537
- imageUrl,
538
- }: {
539
- imageUrl: string;
540
- }): Promise<InferSliceResponse> {
542
+ async inferSlice(
543
+ args: { imageUrl: string } & (
544
+ | { source: "upload" }
545
+ | { source: "figma"; libraryID: string }
546
+ ),
547
+ ): Promise<InferSliceResponse> {
548
+ const { source, imageUrl } = args;
541
549
  const authToken = await this.user.getAuthenticationToken();
542
- const headers = {
543
- Authorization: `Bearer ${authToken}`,
544
- };
545
550
 
546
- const repository = await this.project.getResolvedRepositoryName();
547
- const searchParams = new URLSearchParams({
548
- repository,
549
- });
551
+ if (source === "figma") {
552
+ const { libraryID } = args;
553
+ // eslint-disable-next-line no-console
554
+ console.log(`inferSlice started`);
555
+ const startTime = Date.now();
550
556
 
551
- const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
552
- url.search = searchParams.toString();
557
+ let tmpDir: string | undefined;
558
+ try {
559
+ const config = await this.project.getSliceMachineConfig();
560
+
561
+ let framework:
562
+ | { type: "nextjs" | "nuxt" | "sveltekit"; label: string }
563
+ | undefined;
564
+ if (config.adapter === "@slicemachine/adapter-next") {
565
+ framework = { type: "nextjs", label: "Next.js (React)" };
566
+ } else if (
567
+ config.adapter === "@slicemachine/adapter-nuxt" ||
568
+ config.adapter === "@slicemachine/adapter-nuxt2"
569
+ ) {
570
+ framework = { type: "nuxt", label: "Nuxt (Vue)" };
571
+ } else if (config.adapter === "@slicemachine/adapter-sveltekit") {
572
+ framework = { type: "sveltekit", label: "SvelteKit (Svelte)" };
573
+ }
553
574
 
554
- const response = await fetch(url.toString(), {
555
- method: "POST",
556
- headers: headers,
557
- body: JSON.stringify({ imageUrl }),
558
- });
575
+ if (!framework) {
576
+ throw new Error(
577
+ "Could not determine framework from Slice Machine config.",
578
+ );
579
+ }
559
580
 
560
- if (!response.ok) {
561
- throw new Error(`Failed to infer slice: ${response.statusText}`);
562
- }
581
+ let frameworkFileExtension: string | undefined;
582
+ if (framework.type === "nextjs") {
583
+ frameworkFileExtension = "tsx";
584
+ } else if (framework.type === "nuxt") {
585
+ frameworkFileExtension = "vue";
586
+ } else if (framework.type === "sveltekit") {
587
+ frameworkFileExtension = "svelte";
588
+ }
589
+
590
+ if (!frameworkFileExtension) {
591
+ throw new Error(
592
+ "Could not determine framework from Slice Machine config.",
593
+ );
594
+ }
595
+
596
+ const projectRoot = await this.project.getRoot();
597
+ const libraryAbsPath = path.join(projectRoot, libraryID);
563
598
 
564
- const json = await response.json();
599
+ tmpDir = await mkdtemp(
600
+ path.join(tmpdir(), "slice-machine-infer-slice-tmp-"),
601
+ );
602
+ const tmpImagePath = path.join(tmpDir, `${randomUUID()}.png`);
603
+ const response = await fetch(imageUrl);
604
+ if (!response.ok) {
605
+ throw new Error(
606
+ `Failed to download image: ${response.status} ${response.statusText}`,
607
+ );
608
+ }
609
+ await writeFile(
610
+ tmpImagePath,
611
+ Buffer.from(await response.arrayBuffer()),
612
+ );
613
+
614
+ const queries = queryClaude({
615
+ prompt: `CRITICAL INSTRUCTIONS - READ FIRST:
616
+ - You MUST start immediately with Step 1.1. DO NOT read, analyze, or explore any project files first.
617
+ - Work step-by-step through the numbered tasks below.
618
+ - DO NOT present any summary, explanation, or completion message after finishing.
619
+ - DO NOT create TODO lists while performing tasks.
620
+ - Keep responses minimal - only show necessary tool calls and brief progress notes.
621
+
622
+ # CONTEXT
623
+
624
+ The user wants to build a new Prismic Slice based on a design image they provided.
625
+ Your goal is to analyze the design image and generate the JSON model data and boilerplate code for the slice following Prismic requirements.
626
+
627
+ You will work under the slice library at <slice_library_path>, where all the slices are stored.
628
+
629
+ # AVAILABLE RESOURCES
630
+
631
+ <design_image_path>
632
+ ${tmpImagePath}
633
+ </design_image_path>
634
+
635
+ <slice_library_path>
636
+ ${libraryAbsPath}
637
+ </slice_library_path>
638
+
639
+ <framework>
640
+ ${framework.label}
641
+ </framework>
642
+
643
+ # AVAILABLE TOOLS
644
+
645
+ You have access to specialized Prismic MCP tools for this task:
646
+
647
+ <tool name="mcp__prismic__how_to_model_slice">
648
+ <description>
649
+ Provides detailed guidance on creating Prismic slice models, including field types, naming conventions, and best practices.
650
+ </description>
651
+ <when_to_use>
652
+ Call this tool in Step 2.1 to learn how to structure the slice model data for the design you analysed.
653
+ </when_to_use>
654
+ </tool>
655
+
656
+ <tool name="mcp__prismic__how_to_code_slice">
657
+ <description>
658
+ Provides guidance on implementing Prismic slice components, including how to use Prismic field components, props structure, and best practices.
659
+ </description>
660
+ <when_to_use>
661
+ Call this tool in Step 2.1 to learn how to properly structure the slice component with Prismic fields.
662
+ </when_to_use>
663
+ </tool>
664
+
665
+ <tool name="mcp__prismic__save_slice_data">
666
+ <description>
667
+ Validates and saves the slice model data to model.json. This is the ONLY way to create the model file.
668
+ </description>
669
+ <when_to_use>
670
+ Call this tool in Step 2.3 after you have built the complete slice model structure in memory.
671
+ </when_to_use>
672
+ </tool>
673
+
674
+ # TASK REQUIREMENTS
675
+
676
+ ## Step 1: Gather information from the design image
677
+ 1.1. Analyse the design image at <design_image_path>.
678
+ 1.2. Identify all elements in the image that should be dynamically editable (e.g., headings, paragraphs, images, links, buttons, etc.).
679
+ 1.3. List the slice directories under <slice_library_path>.
680
+ 1.4. Come up with a unique name for the new slice based on the content of the image and the slice directories.
681
+
682
+ ## Step 2: Model the Prismic slice
683
+ 2.1. Call mcp__prismic__how_to_model_slice to learn how to structure the model for this design.
684
+ - Make sure the name you use for the new slice does not yet exist in the slice library at <slice_library_path>. If it does, use a different name.
685
+ 2.2. Build the complete slice JSON model data in memory based on the guidance received and the information extracted from the image.
686
+ 2.3. Call mcp__prismic__save_slice_data to save the model (DO NOT manually write model.json) in the slice library at <slice_library_path>.
687
+
688
+ ## Step 3: Code a boilerplate slice component based on the model
689
+ 3.1. Call mcp__prismic__how_to_code_slice to learn how to properly structure the slice component with Prismic fields.
690
+ 3.2. Update the slice component code at <slice_library_path>/index.${frameworkFileExtension}, replacing the placeholder code with boilerplate code with the following requirements:
691
+ - Must NOT be based on existing slices or components from the codebase.
692
+ - Must render all the Prismic components to display the fields of the slice model created at <slice_model_path>.
693
+ - Must be a valid ${framework.label} component.
694
+ - Must NOT have any styling/CSS. No inlines styles or classNames. Just the skeleton component structure.
695
+ - Must NOT use any other custom component or functions from the user's codebase.
696
+ - Avoid creating unnecessary wrapper elements, like if they only wrap a single component (e.g., <div><PrismicRichText /></div>).
697
+
698
+ ## Step 4: Present the newly created slice path
699
+ 4.1. Present the path to the newly created slice in the following format: <new_slice_path>${libraryAbsPath}/MyNewSlice</new_slice_path>.
700
+ - "MyNewSlice" must be the name of the directory of the newly created slice.
701
+
702
+ # EXAMPLE OF CORRECT EXECUTION
703
+
704
+ <example>
705
+ Assistant: Step 1.1: Analysing design image...
706
+ [reads <design_image_path>]
707
+
708
+ Step 1.2: Identifying editable content elements...
709
+ [identifies: title field, description field, buttonText field, buttonLink field, backgroundImage field]
710
+
711
+ Step 1.3: Listing slice directories under <slice_library_path>...
712
+ [lists slice directories: Hero, Hero2, Hero3]
713
+
714
+ Step 1.4: Coming up with a unique name for the new slice...
715
+ [comes up with a unique name for the new slice: Hero4]
716
+
717
+ Step 2.1: Getting Prismic modeling guidance...
718
+ [calls mcp__prismic__how_to_model_slice]
719
+
720
+ Step 2.2: Building slice model based on guidance and the information extracted...
721
+ [creates model with title field, description field, buttonText field, buttonLink field, backgroundImage field]
722
+
723
+ Step 2.3: Saving slice model...
724
+ [calls mcp__prismic__save_slice_data]
725
+
726
+ Step 3.1: Learning Prismic slice coding requirements...
727
+ [calls mcp__prismic__how_to_code_slice]
728
+
729
+ Step 3.2: Coding boilerplate slice component based on the model...
730
+ [updates component with Prismic field components, no styling, no other components]
731
+
732
+ Step 4.1: Presenting the path to the newly created slice...
733
+ [presents <new_slice_path>${path.join(
734
+ libraryAbsPath,
735
+ "MyNewSlice",
736
+ )}</new_slice_path>]
737
+
738
+ # DELIVERABLES
739
+ - Slice model saved to <slice_library_path>/model.json using mcp__prismic__save_slice_data
740
+ - Slice component at <slice_library_path>/index.${frameworkFileExtension} updated with boilerplate code
741
+ - New slice path presented in the format mentioned in Step 3.1
742
+
743
+ YOU ARE NOT FINISHED UNTIL YOU HAVE THESE DELIVERABLES.
744
+
745
+ ---
746
+
747
+ FINAL REMINDERS:
748
+ - You MUST use mcp__prismic__save_slice_data to save the model
749
+ - You MUST call mcp__prismic__how_to_code_slice in Step 3.1
750
+ - DO NOT ATTEMPT TO BUILD THE APPLICATION
751
+ - START IMMEDIATELY WITH STEP 1.1 - NO PRELIMINARY ANALYSIS;`,
752
+ options: {
753
+ cwd: libraryAbsPath,
754
+ stderr: (data) => console.error(data),
755
+ model: "claude-haiku-4-5",
756
+ permissionMode: "bypassPermissions",
757
+ allowedTools: [
758
+ "Bash",
759
+ "Read",
760
+ "FileSearch",
761
+ "Grep",
762
+ "Glob",
763
+ "Task",
764
+ "Edit",
765
+ "Write",
766
+ "MultiEdit",
767
+ "mcp__prismic__how_to_model_slice",
768
+ "mcp__prismic__how_to_code_slice",
769
+ "mcp__prismic__save_slice_data",
770
+ ],
771
+ disallowedTools: [
772
+ `Edit(**/model.json)`,
773
+ `Write(**/model.json)`,
774
+ "Edit(**/mocks.json)",
775
+ "Write(**/mocks.json)",
776
+ ],
777
+ env: {
778
+ ...process.env,
779
+ ANTHROPIC_BASE_URL: API_ENDPOINTS.LlmProxyTypeService,
780
+ ANTHROPIC_API_KEY: authToken,
781
+ },
782
+ mcpServers: {
783
+ prismic: {
784
+ type: "stdio",
785
+ command: "npx",
786
+ args: ["-y", "@prismicio/mcp-server@0.0.20-alpha.6"],
787
+ },
788
+ },
789
+ },
790
+ });
565
791
 
566
- return InferSliceResponse.parse(json);
792
+ let newSliceAbsPath: string | undefined;
793
+
794
+ for await (const query of queries) {
795
+ switch (query.type) {
796
+ case "result":
797
+ if (query.subtype === "success") {
798
+ newSliceAbsPath = query.result.match(
799
+ /<new_slice_path>(.*)<\/new_slice_path>/s,
800
+ )?.[1];
801
+ }
802
+ break;
803
+ }
804
+ }
805
+
806
+ if (!newSliceAbsPath) {
807
+ throw new Error("Could not find path for the newly created slice.");
808
+ }
809
+
810
+ const model = await readFile(
811
+ path.join(newSliceAbsPath, "model.json"),
812
+ "utf8",
813
+ );
814
+
815
+ if (!model) {
816
+ throw new Error("Could not find model for the newly created slice.");
817
+ }
818
+
819
+ // move the screenshot image to the new slice directory
820
+ await rename(
821
+ tmpImagePath,
822
+ path.join(newSliceAbsPath, "screenshot-default.png"),
823
+ );
824
+ await rm(tmpDir, { recursive: true });
825
+
826
+ const elapsedTimeSeconds = (Date.now() - startTime) / 1000;
827
+ // eslint-disable-next-line no-console
828
+ console.log(`inferSlice took ${elapsedTimeSeconds}s`);
829
+
830
+ return InferSliceResponse.parse({ slice: JSON.parse(model) });
831
+ } catch (error) {
832
+ if (tmpDir && existsSync(tmpDir)) {
833
+ await rm(tmpDir, { recursive: true });
834
+ }
835
+
836
+ throw error;
837
+ }
838
+ } else {
839
+ const headers = {
840
+ Authorization: `Bearer ${authToken}`,
841
+ };
842
+
843
+ const repository = await this.project.getResolvedRepositoryName();
844
+ const searchParams = new URLSearchParams({
845
+ repository,
846
+ });
847
+
848
+ const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
849
+ url.search = searchParams.toString();
850
+
851
+ const response = await fetch(url.toString(), {
852
+ method: "POST",
853
+ headers: headers,
854
+ body: JSON.stringify({ imageUrl }),
855
+ });
856
+
857
+ if (!response.ok) {
858
+ throw new Error(`Failed to infer slice: ${response.statusText}`);
859
+ }
860
+
861
+ const json = await response.json();
862
+
863
+ return InferSliceResponse.parse(json);
864
+ }
567
865
  }
568
866
  }
569
867