### Clone and Run Hypergraph Example Application Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/quickstart.md This snippet provides commands to clone, install dependencies, and run a pre-built Hypergraph example application from GitHub, allowing users to quickly see Hypergraph in action. ```bash git clone https://github.com/geobrowser/hypergraph-app-template.git cd hypergraph-app-template pnpm install pnpm dev ``` -------------------------------- ### Run Generated Hypergraph Application Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/quickstart.md Navigates into the newly scaffolded application directory, installs its dependencies using pnpm, and starts the local development server, making the application accessible in the browser. ```bash cd ./my-awesome-app # Adjust the path to match your app's name pnpm install pnpm dev ``` -------------------------------- ### Launch Hypergraph TypeSync Studio Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/quickstart.md Starts the TypeSync server, a visual tool for defining data schemas, and automatically opens it in the browser, accessible at http://localhost:3000. ```bash hg typesync --open ``` -------------------------------- ### Install Hypergraph CLI for Application Scaffolding Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/quickstart.md Installs the latest version of the Hypergraph Command Line Interface globally, a prerequisite for using TypeSync and scaffolding new applications. Includes options for both npm and pnpm. ```npm npm install -g @graphprotocol/hypergraph-cli@latest ``` ```pnpm pnpm install -g @graphprotocol/hypergraph-cli@latest pnpm approve-builds -g # select @tailwindcss/oxide, better-sqlite3, and esbuild ``` -------------------------------- ### Hypergraph Server Initial Setup Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet outlines the initial steps to set up the Hypergraph server application. It involves installing dependencies, navigating to the server directory, configuring environment variables, and running Prisma database migrations. ```sh pnpm install cd apps/server cp .env.example .env # add the PRIVY_APP_SECRET & PRIVY_APP_ID to the apps/server/.env file pnpm prisma migrate dev ``` -------------------------------- ### Setup Hypergraph Development Environment Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Steps to set up the local development environment for Hypergraph, including installing dependencies, configuring environment variables, and running database migrations. ```sh pnpm install cd apps/server cp .env.example .env # add the PRIVY_APP_SECRET & PRIVY_APP_ID to the apps/server/.env file pnpm prisma migrate dev ``` -------------------------------- ### Run Hypergraph Next.js Example Application Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet demonstrates how to run the Next.js example application for Hypergraph. It requires building packages beforehand and navigating to the `apps/next-example` directory to start the development server. ```sh # Notes: # - You need to build the packages first and every time you make changes to the packages cd apps/next-example pnpm dev ``` -------------------------------- ### Clone Hypergraph Repository and Install Dependencies Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/advanced/running-connect-and-sync-server-locally.md This snippet clones the Hypergraph repository from GitHub, navigates into the directory, and installs project dependencies using pnpm. ```bash git clone https://github.com/graphprotocol/hypergraph.git cd hypergraph pnpm install ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/README.md Installs all necessary dependencies for the monorepo from the root directory using pnpm. This command should be run once to set up the project. ```Shell pnpm install ``` -------------------------------- ### Start Hypergraph TypeSync UI Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Command to start the Hypergraph TypeSync user interface, which is the first step in generating a new application. ```bash hypergraph typesync ``` -------------------------------- ### Run a Newly Generated Hypergraph Application Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Instructions to navigate into a newly generated Hypergraph application directory and start its development server using pnpm. ```bash cd awesome-app pnpm dev ``` -------------------------------- ### Install Hypergraph CLI Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Instructions to install the Hypergraph command-line interface globally using npm, yarn, or pnpm package managers. ```bash # npm npm i -g @graphprotocol/hypergraph-cli # yarn yarn global add @graphprotocol/hypergraph-cli # pnpm pnpm install -g @graphprotocol/hypergraph-cli ``` -------------------------------- ### Start Docusaurus Local Development Server Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/README.md Starts a local development server specifically for the Docusaurus documentation site. This command opens a browser window and provides live reflection of most changes without requiring a server restart. ```Shell pnpm --filter docs start ``` -------------------------------- ### Start Hypergraph Connect and Sync Server Locally Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/advanced/running-connect-and-sync-server-locally.md This snippet demonstrates how to start the Connect app and the Sync Server in separate terminal tabs, making them accessible via localhost. ```bash cd apps/connect pnpm dev # in another tab cd apps/server pnpm dev ``` -------------------------------- ### Install Hypergraph SDK Alpha Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/blog/2025-06-11-hypergraph-alpha-released.md Command to install the Hypergraph SDK for developer preview. This is a placeholder and indicates the future npm installation command for the SDK. ```bash # TODO: ADD INSTALLER TO NPM npm install @hypergraph/sdk-alpha ``` -------------------------------- ### Run Hypergraph Documentation Locally Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet provides instructions for running the Hypergraph documentation website locally. It involves navigating to the `docs` directory and executing the start command. ```sh cd docs pnpm start ``` -------------------------------- ### Install and Run Hypergraph TypeSync CLI Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/mapping.md This snippet provides the command-line instructions to globally install the Hypergraph CLI using pnpm. It then shows how to execute the 'typesync' command, which generates the entire mapping structure and automatically opens it for review. ```bash pnpm install -g @graphprotocol/hypergraph-cli@latest hg typesync --open ``` -------------------------------- ### createSpace API Documentation and Examples Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/api-reference.md Comprehensive documentation for the `createSpace` API endpoint, detailing its HTTP/WebSocket methods, authentication, event schema, and providing JSON examples for both request and successful response. This event is used to bootstrap a new space. ```APIDOC Method: POST /spaces (HTTP) or WebSocket event Auth: Signed with the creator's signature key + SIWE cookie Body: See event schema below. Success: 201 Created with { "spaceId": "…" } Errors: 409 AlreadyExists, 401 Unauthorized, 422 InvalidSignature ``` ```typescript export const CreateSpaceEvent = Schema.Struct({ transaction: Schema.Struct({ type: Schema.Literal('create-space'), id: Schema.String, creatorAccountId: Schema.String, }), author: EventAuthor, // { accountId: string, signature: { hex: string, recovery: number } } }); ``` ```json { "eventId": "6db7b5f0", "spaceId": "efc45a11", "transaction": { "type": "create-space", "id": "efc45a11", "creatorAccountId": "did:pkh:eip155:1:0x123..." }, "author": { "accountId": "did:pkh:eip155:1:0x123...", "signature": { "hex": "0xabc...", "recovery": 1 } } } ``` ```json { "spaceId": "efc45a11" } ``` -------------------------------- ### Serve Docusaurus production build locally Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/deploy-your-site.md This command starts a local server to test the production build of your Docusaurus site. It serves the content from the `build` folder, typically accessible at `http://localhost:3000/`, allowing you to verify the deployed version before actual deployment. ```bash npm run serve ``` -------------------------------- ### Start Docusaurus site with specific locale using npm Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/translate-your-site.md This command starts the Docusaurus development server, specifically targeting the French locale. It allows developers to preview the localized version of their site during development, ensuring translations are displayed correctly. ```bash npm run start -- --locale fr ``` -------------------------------- ### Develop Typesync CLI Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet shows how to start the development server for the Typesync CLI. It involves navigating to the Typesync application directory and running the development command. ```sh cd apps/typesync pnpm dev ``` -------------------------------- ### Run Hypergraph Development Servers Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet details how to run the Hypergraph development environment across multiple terminal tabs. It includes building packages with watch mode, starting the events application, and starting the main server application. ```sh pnpm build --watch # in another tab cd apps/events pnpm dev # in another tab cd apps/server pnpm dev ``` -------------------------------- ### Integrate eslint-plugin-react into ESLint Configuration Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/events/README.md This code demonstrates how to integrate `eslint-plugin-react` into your ESLint configuration. It sets the React version, adds the plugin, and enables its recommended rules, including those for JSX runtime. ```JavaScript // eslint.config.js import react from 'eslint-plugin-react' export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }) ``` -------------------------------- ### Develop Typesync Frontend Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet describes the process for developing the Typesync frontend, requiring two separate terminal tabs. It includes starting the CLI development server and the client development server, with a note about modifying the Vite configuration. ```sh # open the vite.config.ts and comment out the server object that specifies the port to be 3000 cd apps/typesync pnpm run dev:cli # in another tab cd apps/typesync pnpm dev:client ``` -------------------------------- ### Create Your First React Page in Docusaurus Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-page.md This snippet demonstrates how to create a new standalone React page in a Docusaurus project. By placing a `.js` file in `src/pages`, Docusaurus automatically creates a route. The example uses the `@theme/Layout` component for consistent page structure and basic HTML content. ```jsx import React from 'react'; import Layout from '@theme/Layout'; export default function MyReactPage() { return (

My React page

This is a React page

); } ``` -------------------------------- ### Configure ESLint parserOptions for Type-Aware Linting Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/events/README.md This configuration snippet shows how to set up `parserOptions` in your ESLint configuration to enable type-aware linting rules. It specifies the `project` paths for TypeScript configuration files and the `tsconfigRootDir`. ```JavaScript export default tseslint.config({ languageOptions: { // other options... parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, }, }) ``` -------------------------------- ### Hypergraph Space Management API Initialization and Usage Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/framework.md This comprehensive snippet illustrates the initialization of Hypergraph's space management API using `createFunctions` and demonstrates common operations such as listing spaces, getting a specific space, and accepting an invite. It highlights the `SpaceProvider` component for context provision and server connection. ```tsx import { createSpace, acceptInvite, createSpace, listSpaces, } from "@graphprotocol/hypergraph"; export const { SpaceProvider, // schema useCreateEntity, useDeleteEntity, useSpaceId, createDocumentId, useQuery, // space utils createInvite, removeInvite, updateMember, removeMember, deleteSpace, listSpaces, getSpace, } = createFunctions(schema, { endpoint: "http://localhost:3000/sync", }); // automatically connects to the server ; listSpaces({ account }); getSpace({ account, spaceId }); acceptInvite({ account, spaceId, inviteKey }); ``` -------------------------------- ### Create Relative and Absolute Links in Markdown Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/markdown-features.mdx These snippets show how to create links in Docusaurus Markdown. The first example uses an absolute path, while the second uses a relative file path to link to another document. ```md Let's see how to [Create a page](/create-a-page). ``` ```md Let's see how to [Create a page](./create-a-page.md). ``` -------------------------------- ### Hypergraph Space Management API Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/framework.md Defines the API endpoints and their parameters for managing spaces, including operations for creating, deleting, inviting, managing members, listing, getting, and sending updates for spaces. ```APIDOC Space Management API: createSpace: Description: Creates a new space. Parameters: eventId: string spaceId: string ciphertext: string nonce: string memberSignaturePublicKey: string memberEncryptionPublicKey: string keyBox: ciphertext: string recipientPublicKey: string authorPublicKey: string signature of the combined data: string deleteSpace: Description: Deletes an existing space. Parameters: eventId: string spaceId: string signature of the combined data: string createInvite: Description: Creates an invitation to a space. Parameters: eventId: string spaceId: string invitationKeysCiphertext: string invitationKeysNonce: string invitationSignaturePublicKey: string invitationEncryptionPublicKey: string lastKnownSpaceEventId: string signature of the combined data: string acceptInvite: Description: Accepts an invitation to a space. Parameters: eventId: string spaceId: string memberSignaturePublicKey: string memberEncryptionPublicKey: string signature of the combined data using the invitationSignaturePublicKey: string signature of the combined data using the member public key: string removeInvite: Description: Removes an invitation and triggers a key rotation for the group. Parameters: eventId: string (automatically becomes the spaceKeyId) spaceId: string inviteId: string lastKnownSpaceEventId: string keyBox: ciphertext: string recipientPublicKey: string authorPublicKey: string signature of the combined data: string updateMember: Description: Updates a member's role in a space (only by space admins). Parameters: eventId: string spaceId: string memberSignaturePublicKey: string role: "editor" | "admin" removeMember: Description: Removes a member from a space and triggers a key rotation. Parameters: eventId: string (automatically becomes the spaceKeyId) spaceId: string memberSignaturePublicKey: string lastKnownSpaceEventId: string keyBoxes: - ciphertext: string recipientPublicKey: string authorPublicKey: string signature of the combined data: string listSpaces: Description: Returns a list of space IDs and removed event IDs. Parameters: None Returns: A list of space Ids and the remove event for the ones that have been removed. The client then can connect get each space separately. getSpace: Description: Retrieves details for a specific space. Automatically happens on WebSocket connect. Parameters: None sendUpdate: Description: Sends an update to a space. Parameters: eventId: string ciphertext: string nonce: string spaceId: string spaceKeyId: string signature of the combined data: string sendCompactedUpdate: Description: Sends a compacted update (snapshot) for a space. Parameters: eventId: string snapshotUntilEventId: string ciphertext: string nonce: string spaceId: string spaceKeyId: string signature of the combined data: string ``` -------------------------------- ### deleteSpace API Documentation and Examples Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/api-reference.md Comprehensive documentation for the `deleteSpace` API endpoint, detailing its HTTP/WebSocket methods, authentication, and event schema. This event is used to soft-delete a space and requires referencing the hash of the previous event for chain integrity. ```APIDOC Method: DELETE /spaces/:id (HTTP) or WebSocket event Auth: admin role in the space Success: 200 OK Errors: 401 Unauthorized, 404 NotFound ``` ```typescript export const DeleteSpaceEvent = Schema.Struct({ transaction: Schema.Struct({ type: Schema.Literal('delete-space'), id: Schema.String, // The ID of the space to delete previousEventHash: Schema.String, }), author: EventAuthor, }); ``` -------------------------------- ### Generate Base58 Encoded ID in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/namespaces/utils.md Demonstrates how to use the generateId() function from @graph-framework/utils to create a base58 encoded ID. The example imports the function and logs the generated ID to the console. ```typescript import { generateId } from "@graph-framework/utils"; const id = generateId(); console.log(id); // Gw9uTVTnJdhtczyuzBkL3X ``` -------------------------------- ### Encode UUID to Base58 String in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/namespaces/utils.md Illustrates encoding a UUID to a base58 string using encodeBase58 from @graph-framework/utils. The example shows generating a UUID, removing hyphens, and then encoding the resulting string. ```typescript import { v4 } from "uuid"; import { encodeBase58 } from "@graph-framework/utils"; const uuid = v4(); // 92539817-7989-4083-ab80-e9c2b2b66669 const stripped = uuid.replaceAll(/-/g, ""); // 9253981779894083ab80e9c2b2b66669 const encoded = encodeBase58(stripped); console.log(encoded); // K51CbDqxW35osbjPo5ZF77 ``` -------------------------------- ### Embed Images in Markdown with Docusaurus Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/markdown-features.mdx These snippets illustrate how to embed images in Docusaurus Markdown. The first example uses an absolute path to an image in the static directory, while the second uses a relative path to an image colocated with the Markdown file. ```md ![Docusaurus logo](/img/docusaurus.png) ``` ```md ![Docusaurus logo](./img/docusaurus.png) ``` -------------------------------- ### End-to-End Data Publishing Flow with Hypergraph React Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/publishing-public-data.md This comprehensive example demonstrates a full data publishing workflow within a React component. It integrates `useHypergraphApp`, `useQuery`, `preparePublish`, and `publishOps` to fetch private events, prepare them for publishing, and then publish them to a public space using a smart session client. It shows how to handle asynchronous operations and user interaction for publishing individual entities. ```tsx import { publishOps, useHypergraphApp } from "@graphprotocol/hypergraph-react"; const MyComponent = ({ publicSpaceId }: { publicSpaceId: string }) => { const { getSmartSessionClient } = useHypergraphApp(); const { data: events } = useQuery(Event, { mode: "private" }); const publishEvent = async (entity) => { const smartSessionClient = await getSmartSessionClient(); const { ops } = preparePublish({ entity: entity, publicSpace: publicSpaceId }); const result = await publishOps({ ops, walletClient: smartSessionClient, space: publicSpaceId, name: "Create Event" }); }; return (
{events.map((event) => ( ))}
); }; ``` -------------------------------- ### Canonicalize JSON Data in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/namespaces/utils.md Demonstrates the canonicalize function for creating crypto-safe, predictable JSON canonicalization. It provides examples for various data types, including null, numbers, strings, booleans, objects, and arrays, showing the consistent output. ```typescript import { canonicalize } from '@graph-framework/utils' console.log(canonicalize(null)) // 'null' console.log(canonicalize(1)) // '1' console.log(canonicalize("test")) // "string" console.log(canonicalize(true)) // 'true' const json = { from_account: '543 232 625-3', to_account: '321 567 636-4', amount: 500, currency: 'USD' }; console.log(canonicalize(json)) // '{"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"}' console.log(canonicalize([1, 'text', null, true, false])) // '[1,"text",null,true,false]' ``` -------------------------------- ### Define Entity Schema with Relation for Filtering Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This snippet defines a 'Todo' entity class, including a 'Type.Relation' to a 'User' entity. This schema setup is foundational for demonstrating how to filter queries based on related entities. ```tsx // schema export class Todo extends Entity.Class('Todo')({ name: Type.Text, checked: Type.Checkbox, assignees: Type.Relation(User), }) ``` -------------------------------- ### Decode Base58 String to UUID in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/namespaces/utils.md Shows how to decode a base58 encoded string back into its original UUID format using decodeBase58ToUUID. The example includes encoding a UUID first and then verifying that the decoded value matches the original UUID. ```typescript import { v4 } from "uuid"; import { decodeBase58ToUUID, encodeBase58 } from "@graph-framework/utils"; const uuid = v4(); // 92539817-7989-4083-ab80-e9c2b2b66669 const stripped = uuid.replaceAll(/-/g, ""); // 9253981779894083ab80-e9c2b2b66669 const encoded = encodeBase58(stripped); // K51CbDqxW35osbjPo5ZF77 const decoded = decodeBase58ToUUID(encoded); expect(encoded).toHaveLength(22); expect(decoded).toEqual(uuid); ``` -------------------------------- ### Filter API Syntax for Property Types and Logical Operators Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This section outlines the various filter options available for different property types (checkbox, text, number, point) and demonstrates the usage of logical 'not' and 'or' operators within the filter API. It provides examples for exact matches, existence checks, string operations, numerical comparisons, and logical combinations. ```APIDOC // checkbox filter { is: true/false, // exact match exists: true/false, // filter by existence of the property } // text filter { is: "text", // exact match contains: "text", startsWith: "text", endsWith: "text", exists: true/false, // filter by existence of the property } // number filter { is: 42, lessThan: 42, lessThanOrEqual: 42, greaterThan: 42, greaterThanOrEqual: 42, exists: true/false, // filter by existence of the property } // point filter { is: [0, 42], exists: true/false, // filter by existence of the property } // logical `not` for a string { not: { is: "Jane Doe", }, } // logical `or` for a string { or: [ { name: "Jane Doe" }, { name: "John Doe" }, ], } ``` -------------------------------- ### Complex Property Filtering with Logical Operators Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md These examples demonstrate advanced filtering scenarios using the 'useQuery' hook. They show how to combine multiple logical operators ('or', 'not') and property-specific filters (e.g., 'age', 'name') to retrieve data based on intricate conditions. ```tsx // ever person except if their name is not Jane Doe or John Doe const { data } = useQuery(Person, { filter: { or: [ not: { name: { is: "Jane Doe" } }, not: { name: { is: "John Doe" } }, ], }, }); // ever person that is 42, but their name is not Jane Doe or John Doe const { data } = useQuery(Person, { filter: { age: { equals: 42 }, or: [ not: { name: { is: "Jane Doe" } }, not: { name: { is: "John Doe" } }, ], not: { or: [ { name: { is: "Jane Doe" } }, { name: { is: "John Doe" } }, ], }, }, }); // every person that is not 42 years old const { data } = useQuery(Person, { filter: { age: { not: { is: 42 }, }, }, }); ``` -------------------------------- ### Define Basic Hypergraph Type with Text Properties in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/schema.md This TypeScript example demonstrates how to define a basic Hypergraph Type, 'Event', using `Entity.Class`. It includes two text properties, `name` and `description`, showcasing the fundamental structure for data modeling within the Hypergraph schema. This snippet is a foundational step for creating custom data entities. ```typescript import { Entity, Type } from '@graphprotocol/hypergraph'; export class Event extends Entity.Class('Event')({ name: Type.Text, description: Type.Text, }) {} ``` -------------------------------- ### Include Related Entities in Public Data Queries Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/query-public-data.md This example shows how to fetch related entities alongside the main data by utilizing the `include` parameter within the `useQuery` hook. It supports including relations up to two levels deep for public data, allowing for more comprehensive data retrieval. ```typescript const { data, isPending, isError } = useQuery(Event, { mode: 'public', include: { sponsors: {} }, }); ``` -------------------------------- ### Combine Logical OR and NOT Filters Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This snippet illustrates how to combine logical 'or' and 'not' operators within the filter API to create more complex query conditions. It shows an example of an 'or' clause containing multiple 'not' conditions. ```APIDOC { or: [ not: { name: "Jane Doe" }, not: { name: "John Doe" }, ], } ``` -------------------------------- ### Define Hypergraph Types with Relations in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/schema.md This TypeScript example illustrates how to establish relations between Hypergraph Types. It defines a 'Company' type and an 'Event' type. The 'Event' type includes a `sponsors` property, which is defined as a `Type.Relation` to the 'Company' type, demonstrating how to link different entities within the Hypergraph schema. This enables complex data relationships. ```typescript import { Entity, Type } from '@graphprotocol/hypergraph'; export class Company extends Entity.Class('Company')({ name: Type.Text, }) {} export class Event extends Entity.Class('Event')({ name: Type.Text, description: Type.Text, sponsors: Type.Relation(Company), }) {} ``` -------------------------------- ### Define Hypergraph Type with Diverse Data Types in TypeScript Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/schema.md This TypeScript example showcases the usage of various available Hypergraph data types within a 'Company' entity. It defines properties such as `name` (Type.Text), `employees` (Type.Number), `founded` (Type.Date), `active` (Type.Checkbox), and `location` (Type.Point). This demonstrates the flexibility of the Hypergraph schema in accommodating different data formats for entity properties. ```typescript import { Entity, Type } from '@graphprotocol/hypergraph'; export class Company extends Entity.Class('Company')({ name: Type.Text, employees: Type.Number, founded: Type.Date, active: Type.Checkbox, location: Type.Point, }) {} ``` -------------------------------- ### Build Docusaurus site for production Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/deploy-your-site.md This command compiles your Docusaurus project into static HTML, JavaScript, and CSS files, preparing it for deployment. The generated files are placed in the `build` directory. ```bash npm run build ``` -------------------------------- ### Deploy SyncServer to Fly.io (Single Instance) Source: https://github.com/graphprotocol/hypergraph/blob/main/CONTRIBUTING.md This set of commands outlines the process for deploying a single instance of the SyncServer to Fly.io. It involves creating a data volume for SQLite, setting necessary environment secrets (DATABASE_URL, Privy app secrets, Hypergraph chain), and finally launching the application with `ha=false` to prevent multiple instances. A final `fly scale count 1` command ensures only one instance is running. ```sh # change the name of the `app` and `primary_region` in the fly.toml file # create a volume for the sqlite db file - replace `fra` with your region fly volumes create data -s 1 -r fra # set the DATABASE_URL (not sure if it's necessary since already set in the Dockerfile) fly secrets set DATABASE_URL=file:/data/production.sqlite # set the Privy app secret, id and chain (fill in your values) fly secrets set PRIVY_APP_SECRET= fly secrets set PRIVY_APP_ID= fly secrets set HYPERGRAPH_CHAIN= # deploy (ha=false to avoid starting multiple instances) fly launch --ha=false # probably not necessary, but better safe than sorry fly scale count 1 ``` -------------------------------- ### Hypergraph `typesync` Command Reference Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Documentation for the `hypergraph typesync` command, which launches the Hypergraph API and client UI for schema viewing, knowledge graph browsing, and schema creation. Includes details on optional arguments. ```APIDOC Command: typesync Description: runs the Hypergraph API and client UI application for viewing created application schemas, browsing the Knowledge Graph, and creating new application schemas. Usage: hypergraph typesync Arguments: port: Type: OPTIONAL Default: 3000 Description: port to run the application on Example: hypergraph typesync --port 3001 browser: Type: OPTION Default: 'browser' Description: browser to open the app in, if the --open flag is passed Example: hypergraph typesync --open --browser firefox ``` -------------------------------- ### Create Your First Markdown Page in Docusaurus Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-page.md This snippet shows how to create a simple standalone Markdown page in a Docusaurus project. Placing a `.md` or `.mdx` file in `src/pages` automatically generates a corresponding route. This method is ideal for static content and simple documentation pages. ```mdx # My Markdown page This is a Markdown page ``` -------------------------------- ### Build Docusaurus Static Site Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/README.md Generates static content for the Docusaurus site into the 'build' directory. The output can then be served using any standard static content hosting service. ```Shell pnpm --filter docs build ``` -------------------------------- ### Build Docusaurus site for all locales using npm Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/translate-your-site.md This command builds the Docusaurus site, generating static assets for all configured locales simultaneously. This is typically used for deploying a multi-language site where all translations are served from the same build output. ```bash npm run build ``` -------------------------------- ### Publish Hypergraph Project Packages Source: https://github.com/graphprotocol/hypergraph/blob/main/CONTRIBUTING.md This sequence of commands builds the project and then publishes individual packages: `hypergraph`, `hypergraph-react`, and `typesync`. Each package is published from its respective `publish` directory, with `typesync` specifically tagged as `latest`. ```sh pnpm build # publish hypergraph cd packages/hypergraph/publish pnpm publish # publish hypergraph-react cd packages/hypergraph-react/publish pnpm publish # publish typesync cd apps/typesync pnpm publish --tag latest ``` -------------------------------- ### Deploy Docusaurus Site Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/README.md Deploys the Docusaurus website. This command builds the site and pushes to the 'gh-pages' branch if GitHub Pages is used for hosting. Two variations are provided for deployment with or without SSH. ```Shell USE_SSH=true pnpm --filter docs deploy ``` ```Shell GIT_USER= pnpm --filter docs deploy ``` -------------------------------- ### Create a Docusaurus Blog Post Markdown File Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-blog-post.md This code snippet demonstrates the structure of a Markdown file used to define a new blog post in Docusaurus. It includes YAML front matter for metadata such as the post's slug, title, author details (name, title, URL, image), and associated tags, followed by the main content of the blog post. ```Markdown --- slug: greetings title: Greetings! authors: - name: Joel Marcey title: Co-creator of Docusaurus 1 url: https://github.com/JoelMarcey image_url: https://github.com/JoelMarcey.png - name: Sébastien Lorber title: Docusaurus maintainer url: https://sebastienlorber.com image_url: https://github.com/slorber.png tags: [greetings] --- Congratulations, you have made your first post! Feel free to play around and edit this post as much as you like. ``` -------------------------------- ### Filter Query Results by One-Level Relation Property Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This example shows how to filter query results based on a property of a directly related entity. It demonstrates fetching 'Person' data and filtering by the 'name' property of the 'assignees' relation. ```tsx const { data } = useQuery(Person, { filter: { assignees: { name: { is: "John" }, }, }, }); ``` -------------------------------- ### Create a Basic Markdown Document Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-document.md This snippet demonstrates how to create a simple Markdown file that Docusaurus recognizes as a document. It defines the basic content for a new page, making it accessible via a URL. ```md # Hello This is my **first Docusaurus document**! ``` -------------------------------- ### Build Docusaurus site for specific locale using npm Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/translate-your-site.md This command builds the Docusaurus site, generating static assets specifically for the French locale. This is used for deploying a single-language version of the site or for testing a specific localized build. ```bash npm run build -- --locale fr ``` -------------------------------- ### Copy Docusaurus document for French translation using Bash Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/translate-your-site.md This bash script creates the necessary directory structure for French translations and copies the original 'intro.md' file into the French i18n folder. This prepares the document for localization by providing a template to be translated. ```bash mkdir -p i18n/fr/docusaurus-plugin-content-docs/current/ cp docs/intro.md i18n/fr/docusaurus-plugin-content-docs/current/intro.md ``` -------------------------------- ### Filter Query Results by Relation Entity Property Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This example demonstrates how to filter query results based on properties defined directly on the relation entity itself. It shows fetching 'Person' data and filtering by the 'assignedAt' property within the '_relation' object of the 'assignees' relation. ```tsx const { data } = useQuery(Person, { filter: { assignees: { _relation: { entity: { assignedAt: { greaterThan: new Date("2025-01-01") } }, }, name: { is: "John" }, }, }, }); ``` -------------------------------- ### Access Relation Entity Properties in JSX Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/filtering-query-results.md This snippet provides an example of how to access properties of the relation entity within a React component's JSX. It shows iterating through 'assignees' and displaying both the relation entity's 'assignedAt' property and the related entity's 'name'. ```tsx { todo.assignees.map((assignee) => ( {assignee._relation.entity.assignedAt} {assignee.name} )); } ``` -------------------------------- ### Run Hypergraph Development Components Source: https://github.com/graphprotocol/hypergraph/blob/main/apps/typesync/README.md Commands to concurrently run different Hypergraph application components (build, events, server, typesync) in development mode, typically in separate terminal tabs. ```sh pnpm build --watch # in another tab cd apps/events pnpm dev # in another tab cd apps/server pnpm dev # in another tab cd apps/typesync pnpm build # then, from anywhere in the repo, start Typesync hypergraph typesync ``` -------------------------------- ### Update Hypergraph Server Schema Source: https://github.com/graphprotocol/hypergraph/blob/main/README.md This snippet provides the command to run when schema changes are made in the Hypergraph server. It navigates to the server directory and executes Prisma migrations, which also generates the Prisma client. ```sh cd apps/server pnpm prisma migrate dev # this will also generate the Prisma client ``` -------------------------------- ### Configure Document Sidebar Label and Position with Frontmatter Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-document.md This Markdown snippet illustrates how to add frontmatter to a document to customize its appearance and position within the Docusaurus sidebar. It allows setting a custom label and a specific display order for the document. ```md --- sidebar_label: 'Hi!' sidebar_position: 3 --- # Hello This is my **first Docusaurus document**! ``` -------------------------------- ### Define Sidebar Structure in sidebars.js Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/create-a-document.md This JavaScript snippet shows how to explicitly define the sidebar structure in Docusaurus's `sidebars.js` file. It demonstrates how to include individual documents and categorize them, providing fine-grained control over navigation. ```js export default { tutorialSidebar: [ 'intro', 'hello', { type: 'category', label: 'Tutorial', items: ['tutorial-basics/create-a-document'], }, ], }; ``` -------------------------------- ### Create Docusaurus Documentation Version Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/manage-docs-versions.md This command creates a new version of your Docusaurus documentation. It copies the current `docs` folder into a version-specific directory (e.g., `versioned_docs/version-1.0`) and updates `versions.json`. This results in two distinct documentation sets: the newly versioned content and the 'current' unreleased content. ```bash npm run docusaurus docs:version 1.0 ``` -------------------------------- ### Accept Invitation API Endpoint and Schema Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/api-reference.md API endpoint and event schema for accepting an invitation to join a space. This action adds the user to the member list and requires a signature from the invited account for authorization. The schema defines the structure of the AcceptInvitationEvent, including transaction details and the author of the event. ```APIDOC Method: POST /invites/:id/accept (HTTP) or WebSocket event Auth: Signature from the invited account Success: 200 OK Errors: 401 Unauthorized, 404 NotFound ``` ```typescript export const AcceptInvitationEvent = Schema.Struct({ transaction: Schema.Struct({ type: Schema.Literal('accept-invitation'), id: Schema.String, // The ID of the space previousEventHash: Schema.String, }), author: EventAuthor, // The new member }); ``` -------------------------------- ### Create Admonition Callouts in Docusaurus Markdown Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-basics/markdown-features.mdx These snippets show the Docusaurus-specific syntax for creating admonition blocks (like tips and dangers). These callouts help highlight important information within the documentation. ```md :::tip My tip Use this awesome feature option ::: ``` ```md :::danger Take care This action is dangerous ::: ``` -------------------------------- ### Create Invitation API Endpoint and Schema Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/api-reference.md API endpoint and event schema for creating a new single-use invitation for an account to join a space. It supports both HTTP POST and WebSocket events, requiring an 'admin' role for authorization. The schema defines the structure of the CreateInvitationEvent, including transaction details, invitee account ID, and previous event hash. ```APIDOC Method: POST /spaces/:id/invites (HTTP) or WebSocket event Auth: admin role in the space Success: 201 Created Errors: 401 Unauthorized, 404 NotFound, 422 Unprocessable Entity ``` ```typescript export const CreateInvitationEvent = Schema.Struct({ transaction: Schema.Struct({ type: Schema.Literal('create-invitation'), id: Schema.String, // The ID of the space inviteeAccountId: Schema.String, // The account ID of the user being invited previousEventHash: Schema.String, }), author: EventAuthor, }); ``` -------------------------------- ### Configure Hypergraph Application Provider Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/providers.md The `HypergraphAppProvider` serves as the primary context provider for the Hypergraph application. It requires a `mapping` prop to link your schema with the public Knowledge Graph and optionally accepts a `syncServerUri` for custom sync server endpoints. ```tsx import { HypergraphAppProvider } from "@graphprotocol/hypergraph-react"; const App = () => { return ( ); }; ``` ```APIDOC Component: HypergraphAppProvider Props: mapping: object (mandatory) Description: Mapping of your schema to the public Knowledge Graph schema. syncServerUri: string (optional) Description: URL of the sync server. Default: "https://hypergraph.fly.dev" ``` -------------------------------- ### API Event List Overview Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/api-reference.md Summary of Hypergraph SDK events, their corresponding helper functions, HTTP/WebSocket paths, authentication requirements, and descriptions. All payloads are JSON objects transported over either WebSocket or HTTP. ```APIDOC Event List: - Event: createSpace Helper: createSpace() HTTP / WS Path: /spaces (POST) Auth: SIWE + signature Description: Bootstrap a new Space. - Event: deleteSpace Helper: deleteSpace() HTTP / WS Path: /spaces/:id (DELETE) Auth: admin Description: Soft-delete a Space. - Event: createInvite Helper: inviteToSpace() HTTP / WS Path: /spaces/:id/invites (POST) Auth: admin Description: Create an invitation to a Space. - Event: acceptInvite Helper: acceptInvitation() HTTP / WS Path: /invites/:id/accept (POST) Auth: Invite signature Description: Accept an invitation & join a Space. - Event: createSpaceInbox Helper: createInbox() HTTP / WS Path: /spaces/:id/inboxes (POST) Auth: admin Description: Create a new inbox in a Space. - Event: sendUpdate Helper: _internal_ HTTP / WS Path: /updates (WS) Auth: member Description: Send a CRDT patch to peers. - Event: sendCompactedUpdate Helper: _internal_ HTTP / WS Path: /updates (WS) Auth: member Description: Send a snapshot of the update log. Payloads are JSON objects transported over either WebSocket (default for low-latency real-time sync) or HTTP (optional fallback for bootstrapping or server-to-server calls). ``` -------------------------------- ### Public Graph API GraphQL Endpoint (APIDOC) Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/public-graph-integration.md This API documentation entry provides the direct URL for the GraphiQL interface associated with the public Graph API. This endpoint allows developers to interactively explore the GraphQL schema, test queries, and understand the available data structures and operations. ```APIDOC GraphiQL: https://kg.thegraph.com/graphiql ``` -------------------------------- ### Add Docusaurus Docs Version Dropdown to Navbar Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/tutorial-extras/manage-docs-versions.md To enable easy navigation between different documentation versions, a version dropdown can be added to the Docusaurus navbar. This involves modifying the `themeConfig` within `docusaurus.config.js` to include a `docsVersionDropdown` item, which then renders the dropdown in the site's navigation bar. ```js export default { themeConfig: { navbar: { items: [ { type: 'docsVersionDropdown', }, ], }, }, }; ``` -------------------------------- ### Initiate Geo Connect Authentication Redirect Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/authentication.md The `redirectToConnect` function, available via `useHypergraphApp` from `@graphprotocol/hypergraph-react`, initiates the authentication flow by redirecting the user to the Geo Connect application. It requires parameters such as `storage` (e.g., `localStorage`), `connectUrl` (the Geo Connect application URL), `successUrl` (where to redirect after successful authentication), `appId` (a unique identifier for your application), and `redirectFn` (a function to handle the actual browser redirection). ```tsx import { useHypergraphApp } from "@graphprotocol/hypergraph-react"; function Login() { const { redirectToConnect } = useHypergraphApp(); return ( ); } ``` -------------------------------- ### Manage Hypergraph Sync Server Connection with useHypergraphApp Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/providers.md The `useHypergraphApp` hook, available within `HypergraphAppProvider`, manages the sync server connection. It provides `isConnecting` to indicate sync readiness and a `logout` function for user session management. ```tsx import { useHypergraphApp } from "@graphprotocol/hypergraph-react"; const App = () => { const { isConnecting, logout } = useHypergraphApp(); return
{isConnecting ? "Connecting..." : ""}
; }; ``` ```APIDOC Hook: useHypergraphApp Returns: isConnecting: boolean Description: Indicates that syncing private spaces is not yet possible. True if connecting, false otherwise. logout: function Description: A function that logs out the user. ``` -------------------------------- ### Hypergraph Space Lifecycle Events API Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/docs/core-concepts.md This documentation outlines the key lifecycle events for a Hypergraph Space, detailing their purpose and functionality. These events manage the creation, deletion, membership, and invitation processes within a collaborative Space, ensuring secure and verified operations. ```APIDOC Event: `createSpace` Purpose: Bootstrap a new Space and establish its first encryption key. Event: `deleteSpace` Purpose: Mark the Space as deleted (soft delete). Event: `updateMember` Purpose: Promote or demote a member role. Event: `removeMember` Purpose: Kick a member and rotate keys. Event: `createInvite` / `acceptInvite` Purpose: Securely invite users—keys are boxed to the invitee's public key. ``` -------------------------------- ### Fetching Data with useQuery Hook (TypeScript) Source: https://github.com/graphprotocol/hypergraph/blob/main/docs/legacy-files/public-graph-integration.md This TypeScript snippet demonstrates the use of a `useQuery` hook, likely from a data fetching library, to retrieve data. It destructures common state variables such as `isPending`, `isError`, `error`, `data`, and `isFetching`, which are essential for managing asynchronous data operations in a UI. ```typescript const { isPending, isError, error, data, isFetching } = useQuery(Todo) ```