commit 47b9e3c159bc1313bc0c8cf40bd067f98f625222 Author: St. Nebula Date: Thu Apr 23 23:58:59 2026 -0500 Initial commit diff --git a/.agents/skills/developing-genkit-dart/SKILL.md b/.agents/skills/developing-genkit-dart/SKILL.md new file mode 100644 index 0000000..706023b --- /dev/null +++ b/.agents/skills/developing-genkit-dart/SKILL.md @@ -0,0 +1,57 @@ +--- +name: developing-genkit-dart +description: Generates code and provides documentation for the Genkit Dart SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or integrate LLMs into Dart/Flutter applications. +metadata: + genkit-managed: true +--- + +# Genkit Dart + +Genkit Dart is an AI SDK for Dart that provides a unified interface for code generation, structured outputs, tools, flows, and AI agents. + +## Core Features and Usage +If you need help with initializing Genkit (`Genkit()`), Generation (`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings (`ai.embedMany`), streaming, or calling remote flow endpoints, please load the core framework reference: +[references/genkit.md](references/genkit.md) + +## Genkit CLI (recommended) + +The Genkit CLI provides a local development UI for running Flow, tracing executions, playing with models, and evaluating outputs. + +check if the user has it installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash # Native CLI +# OR +npm install -g genkit-cli # Via npm +``` + +**Usage:** +Wrap your run command with `genkit start` to attach the Genkit developer UI and tracing: +```bash +genkit start -- dart run main.dart +``` + +## Plugin Ecosystem +Genkit relies on a large suite of plugins to perform generative AI actions, interface with external LLMs, or host web servers. + +When asked to use any given plugin, always verify usage by referring to its corresponding reference below. You should load the reference when you need to know the specific initialization arguments, tools, models, and usage patterns for the plugin: + +| Plugin Name | Reference Link | Description | +| ---- | ---- | ---- | +| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. | +| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. | +| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. | +| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. | +| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). | +| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. | +| `genkit_shelf` | [references/genkit_shelf.md](references/genkit_shelf.md) | Load for Integrating Genkit Flow actions over HTTP using Dart Shelf. | +| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). | + +## External Dependencies +Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you must use the [schemantic](https://pub.dev/packages/schemantic) library. +To learn how to use schemantic, ensure you read [references/schemantic.md](references/schemantic.md) for how to implement type safe generated Dart code. This is particularly relevant when you encounter symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix. Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill to understand for using Genkit Dart. + +## Best Practices +- Always check that code cleanly compiles using `dart analyze` before generating the final response. +- Always use the Genkit CLI for local development and debugging. diff --git a/.agents/skills/developing-genkit-dart/references/genkit.md b/.agents/skills/developing-genkit-dart/references/genkit.md new file mode 100644 index 0000000..7dd33e5 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit.md @@ -0,0 +1,380 @@ +# Genkit Core Framework + +Genkit Dart is an AI SDK for Dart that provides a unified interface for text generation, structured output, tool calling, and agentic workflows. + +## Initialization + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; // Or any other plugin + +void main() async { + // Pass plugins to use into the Genkit constructor + final ai = Genkit(plugins: [googleAI()]); +} +``` + +## Generate Text + +```dart +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), // Needs a model reference from a plugin + prompt: 'Explain quantum computing in simple terms.', +); + +print(response.text); +``` + +## Stream Responses +```dart +final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a short story about a robot learning to paint.', +); + +await for (final chunk in stream) { + print(chunk.text); +} +``` + +## Embed Text +```dart +final embeddings = await ai.embedMany( + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], + embedder: googleAI.textEmbedding('text-embedding-004'), +); + +print(embeddings.first.embedding); +``` + +## Define Tools +Models can use define actions and access external data via custom defined tools. +Requires the `schemantic` library for schema definitions. + +```dart +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $WeatherInput { + String get location; +} + +final weatherTool = ai.defineTool( + name: 'getWeather', + description: 'Gets the current weather for a location', + inputSchema: WeatherInput.$schema, + fn: (input, _) async { + // Call your weather API here + return 'Weather in ${input.location}: 72°F and sunny'; + }, +); + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'What\'s the weather like in San Francisco?', + toolNames: ['getWeather'], // Use the tools +); +``` + +## Structured Output + +You can ensure the generative model returns a typed JSON object by providing an `outputSchema`. + +```dart +@Schema() +abstract class $Person { + String get name; + int get age; +} + +// ... inside main ... + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Generate a person named John Doe, age 30', + outputSchema: Person.$schema, // Force the model to return this schema +); + +final person = response.output; // Typed Person object +print('Name: ${person.name}, Age: ${person.age}'); +``` + +## Define Flows +Wrap your AI logic in flows for better observability, testing, and deployment: + +```dart +final jokeFlow = ai.defineFlow( + name: 'tellJoke', + inputSchema: .string(), + outputSchema: .string(), + fn: (topic, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about $topic', + ); + return response.text; // Value return + }, +); + +final joke = await jokeFlow('programming'); +print(joke); +``` + +### Streaming Flows +Stream data from your flows using `context.sendChunk(...)` and returning the final value: + +```dart +final streamStory = ai.defineFlow( + name: 'streamStory', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), + fn: (topic, context) async { + final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a story about $topic', + ); + + await for (final chunk in stream) { + context.sendChunk(chunk.text); // Stream the chunks + } + return 'Story complete'; // Value return + }, +); +``` + +## Calling remote Flows from a dart client +The `genkit` package provides `package:genkit/client.dart` representing remote Genkit actions that can be invoked or streamed using type-safe definitions. + +1. Defines a remote action +```dart +import 'package:genkit/client.dart'; + +final stringAction = defineRemoteAction( + url: 'http://localhost:3400/my-flow', + inputSchema: .string(), + outputSchema: .string(), +); +``` + +2. Call the Remote Action (Non-streaming) +```dart +final response = await stringAction(input: 'Hello from Dart!'); +print('Flow Response: $response'); +``` + +3. Call the Remote Action (Streaming) +Use the `.stream()` method on the action flow, and access `stream.onResult` to wait on the async return value. +```dart +final streamAction = defineRemoteAction( + url: 'http://localhost:3400/stream-story', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), +); + +final stream = streamAction.stream( + input: 'Tell me a short story about a Dart developer.', +); + +await for (final chunk in stream) { + print('Chunk: $chunk'); +} + +final finalResult = await stream.onResult; +print('\nFinal Response: $finalResult'); +``` + +## Calling remote Flows from a Javascript client + +Install `genkit` npm package: + +```bash +npm install genkit +``` + +1. Call a remote flow (non-streaming) + +```ts +import { runFlow } from 'genkit/beta/client'; + +async function callHelloFlow() { + try { + const result = await runFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Genkit User' }, + }); + console.log('Non-streaming result:', result.greeting); + } catch (error) { + console.error('Error calling helloFlow:', error); + } +} + +callHelloFlow(); +``` + +2. Call a remote flow (streaming) + +```ts +import { streamFlow } from 'genkit/beta/client'; + +async function streamHelloFlow() { + try { + const result = streamFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Streaming User' }, + }); + + // Process the stream chunks as they arrive + for await (const chunk of result.stream) { + console.log('Stream chunk:', chunk); + } + + // Get the final complete response + const finalOutput = await result.output; + console.log('Final streaming output:', finalOutput.greeting); + } catch (error) { + console.error('Error streaming helloFlow:', error); + } +} + +streamHelloFlow(); +``` + +## Data Models + +Genkit uses standard data models for representing prompts (messages & parts) and responses. These classes are implemented using schemantic library. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $MyDataModel { + // uses Genkit's Message schema (not schemantic's Message) + List<$Message> get messages; + List<$Part> get parts; +} + +void example() { + // --- Parts --- + // A Text part + final textPart = TextPart(text: 'some text', metadata: {'foo': 'bar'}); + + // A Media/Image part + final mediaPart = MediaPart( + media: Media(url: 'https://...', contentType: 'image/png'), + metadata: {'foo': 'bar'}, + ); + + // A Tool Request initiated by the model + final toolRequestPart = ToolRequestPart( + toolRequest: ToolRequest( + name: 'get_weather', + ref: 'abc', + input: {'location': 'Paris, France'}, + ), + metadata: {'foo': 'bar'}, + ); + + // The resulting data from a Tool execution + final toolResponsePart = ToolResponsePart( + toolResponse: ToolResponse( + name: 'get_weather', + ref: 'abc', + output: {'temperature': '20C'}, + ), + metadata: {'foo': 'bar'}, + ); + + // Model reasoning (e.g. for Claude's "thinking" models) + final reasoningPart = ReasoningPart( + reasoning: 'thinking...', + metadata: {'foo': 'bar'}, + ); + + // A custom fallback part + final customPart = CustomPart( + custom: {'provider': {'specific': 'data'}}, + metadata: {'foo': 'bar'}, + ); + + // --- Messages --- + final systemMessage = Message( + role: Role.system, + content: [textPart, mediaPart], + metadata: {'foo': 'bar'}, + ); + + final userMessage = Message( + role: Role.user, + content: [textPart, mediaPart], // Can contain media (multimodal) + ); + + final modelMessage = Message( + role: Role.model, + // Models can emit text, tool requests, reasoning, or custom parts + content: [textPart, toolRequestPart, reasoningPart, customPart], + ); + + // --- Ergonomic Data Access (schema_extensions.dart) --- + // The Genkit SDK provides extensions on `Message` and `Part` to easily access fields + // without needing to cast them manually. + + // Get concatenated text from all TextParts in a Message + print(modelMessage.text); + + // Get the first Media object from a Message + print(modelMessage.media?.url); + + // Iterate over tool requests in a Message + for (final toolReq in modelMessage.toolRequests) { + print(toolReq.name); + } + + // Inspect individual parts + for (final part in modelMessage.content) { + if (part.isText) print(part.text); + if (part.isMedia) print(part.media?.url); + if (part.isToolRequest) print(part.toolRequest?.name); + if (part.isToolResponse) print(part.toolResponse?.name); + if (part.isReasoning) print(part.reasoning); + if (part.isCustom) print(part.custom); + } + + // --- Streaming Chunks --- + // Data emitted by ai.generateStream() calls + final generateResponseChunk = ModelResponseChunk( + content: [textPart], + index: 0, // Index of the message this chunk belongs to + aggregated: false, + ); + + // Chunks also have text and media accessors + print(generateResponseChunk.text); + + // --- Advanced: Schemas --- + // Use Genkit type schemas directly in Schemantic validations + final messageSchema = Message.$schema; + final partSchema = Part.$schema; + + final mySchema = SchemanticType.map( + .string(), + .list(Message.$schema), // Requires a list of Messages + ); + + // --- Generate Response --- + // ai.generate() returns a GenerateResponseHelper which provides ergonomic getters + // over the underlying ModelResponse: + final response = await ai.generate(...); + + print(response.text); // Concatenated text + print(response.media?.url); // First media part + print(response.toolRequests); // All tool requests + print(response.interrupts); // Tool requests that triggered an interrupt + print(response.messages); // Full history of the conversation, including the request and response + print(response.output); // Structured typed output (if outputSchema was used) +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md new file mode 100644 index 0000000..2e420a3 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md @@ -0,0 +1,41 @@ +# Genkit Anthropic Plugin (`genkit_anthropic`) + +The Anthropic plugin for Genkit Dart, used for interacting with the Claude models. + +## Usage + +Requires `ANTHROPIC_API_KEY` to be passed to the init block. + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_anthropic/genkit_anthropic.dart'; + +void main() async { + final ai = Genkit( + plugins: [anthropic(apiKey: Platform.environment['ANTHROPIC_API_KEY']!)], + ); + + final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Claude Thinking Configurations + +Provides specific configurations for utilizing Claude 3.7+ "thinking" model capabilities. + +```dart +final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Solve this 24 game: 2, 3, 10, 10', + config: AnthropicOptions(thinking: ThinkingConfig(budgetTokens: 2048)), +); + +// The thinking content is available in the message parts +print(response.message?.content); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_chrome.md b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md new file mode 100644 index 0000000..8152369 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md @@ -0,0 +1,23 @@ +# Genkit Chrome AI Plugin (`genkit_chrome`) + +Chrome Built-in AI (Gemini Nano) plugin for Genkit Dart, allowing local offline execution within a Chrome application. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_chrome/genkit_chrome.dart'; + +void main() async { + final ai = Genkit(plugins: [ChromeAIPlugin()]); + + final stream = ai.generateStream( + model: modelRef('chrome/gemini-nano'), + prompt: 'Write a story about a robot.', + ); + + await for (final chunk in stream) { + print(chunk.text); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md new file mode 100644 index 0000000..7ec462d --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md @@ -0,0 +1,23 @@ +# Genkit Firebase AI Plugin (`genkit_firebase_ai`) + +The Firebase AI plugin for Genkit Dart, used for interacting with Gemini APIs through Firebase AI Logic. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_firebase_ai/genkit_firebase_ai.dart'; + +void main() async { + // Initialize Genkit with the Firebase AI plugin + final ai = Genkit(plugins: [firebaseAI()]); + + // Generate text + final response = await ai.generate( + model: firebaseAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md new file mode 100644 index 0000000..92d3ec4 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md @@ -0,0 +1,95 @@ +# Genkit Google GenAI Plugin (`genkit_google_genai`) + +The Google AI plugin provides an interface against the official Google AI Gemini API. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; + +void main() async { + // Initialize Genkit with the Google AI plugin + final ai = Genkit(plugins: [googleAI()]); + + // Generate text + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Embeddings + +```dart +final embeddings = await ai.embedMany( + embedder: googleAI.textEmbedding('text-embedding-004'), + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], +); +``` + +## Image Generation + +The plugin also supports image generation models such as `gemini-2.5-flash-image`. + +### Example (Nano Banana) + +```dart +// Define an image generation flow +ai.defineFlow( + name: 'imageGenerator', + inputSchema: .string(defaultValue: 'A banana riding a bike'), + outputSchema: Media.$schema, + fn: (input, context) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-image'), + prompt: input, + ); + if (response.media == null) { + throw Exception('No media generated'); + } + return response.media!; + }, +); +``` + +The media (url field) contain base64 encoded data uri. You can decode it and save it as a file. + +## Text-to-Speech (TTS) + +You can use text-to-speech models to generate audio from text. The generated `Media` object will contain base64 encoded PCM audio in its data URI. + +```dart +// Define a TTS flow +ai.defineFlow( + name: 'textToSpeech', + inputSchema: .string(defaultValue: 'Genkit is an amazing AI framework!'), + outputSchema: Media.$schema, + fn: (prompt, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-preview-tts'), + prompt: prompt, + config: GeminiTtsOptions( + responseModalities: ['AUDIO'], + speechConfig: SpeechConfig( + voiceConfig: VoiceConfig( + prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Puck'), + ), + ), + ), + ); + + if (response.media != null) { + return response.media!; + } + throw Exception('No audio generated'); + }, +); +``` + +Google AI also supports multi-speaker TTS by configuring a `MultiSpeakerVoiceConfig` inside `SpeechConfig`. diff --git a/.agents/skills/developing-genkit-dart/references/genkit_mcp.md b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md new file mode 100644 index 0000000..ce8ddb0 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md @@ -0,0 +1,115 @@ +# Genkit MCP (`genkit_mcp`) + +MCP (Model Context Protocol) integration for Genkit Dart. + +## MCP Host (Recommended) +Connect to one or more MCP servers and aggregate their capabilities into the Genkit registry automatically. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final host = defineMcpHost( + ai, + McpHostOptionsWithCache( + name: 'my-host', + mcpServers: { + 'fs': McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + }, + ), + ); + + // Tools can be discovered and executed dynamically using a wildcard... + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Summarize the contents of README.md', + toolNames: ['my-host:tool/fs/*'], + ); + + // ...or by specifying the exact tool name + final exactResponse = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read README.md', + toolNames: ['my-host:tool/fs/read_file'], + ); +} +``` + +## MCP Client (Advanced / Single Server) +Connecting to a single MCP server with a client object is an advanced usecase for when you need manual control over the client lifecycle. Standalone clients do not automatically register tools into the registry, so they must be passed into `generate` or `defineDynamicActionProvider` manually. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final client = createMcpClient( + McpClientOptions( + name: 'my-client', + mcpServer: McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + ), + ); + + await client.ready(); + + // Retrieve the tools from the connected client + final tools = await client.getActiveTools(ai); + + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read the contents of README.md', + tools: tools, + ); +} +``` + +## MCP Server +Expose Genkit actions (tools, prompts, resources) over MCP. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + ai.defineTool( + name: 'add', + description: 'Add two numbers together', + inputSchema: .map(.string(), .dynamicSChema()), + fn: (input, _) async => (input['a'] + input['b']).toString(), + ); + + ai.defineResource( + name: 'my-resource', + uri: 'my://resource', + fn: (_, _) async => ResourceOutput(content: [TextPart(text: 'my resource')]), + ); + + // Stdio transport by default + final server = createMcpServer(ai, McpServerOptions(name: 'my-server')); + await server.start(); +} +``` + +### Streamable HTTP Transport +```dart +import 'dart:io'; + +final transport = await StreamableHttpServerTransport.bind( + address: InternetAddress.loopbackIPv4, + port: 3000, +); +await server.start(transport); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_middleware.md b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md new file mode 100644 index 0000000..24cff79 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md @@ -0,0 +1,84 @@ +# Genkit Middleware (`genkit_middleware`) + +A collection of useful middleware for Genkit Dart to enhance your agent's capabilities. Register plugins when initializing Genkit: + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_middleware/genkit_middleware.dart'; + +void main() { + final ai = Genkit( + plugins: [ + FilesystemPlugin(), + SkillsPlugin(), + ToolApprovalPlugin(), + ], + ); +} +``` + +## Filesystem Middleware +Allows the agent to list, read, write, and search/replace files within a restricted root directory. + +```dart +final response = await ai.generate( + prompt: 'Check the logs in the current directory.', + use: [ + filesystem(rootDirectory: '/path/to/secure/workspace'), + ], +); +``` + +**Tools Provided:** +- `list_files`, `read_file`, `write_file`, `search_and_replace` + +## Skills Middleware +Injects specialized instructions (skills) into the system prompt from `SKILL.md` files located in specified directories. + +```dart +final response = await ai.generate( + prompt: 'Help me debug this issue.', + use: [ + skills(skillPaths: ['/path/to/skills']), + ], +); +``` + +**Tools Provided:** +- `use_skill`: Retrieve the full content of a skill by name. + +## Tool Approval Middleware +Intercepts tool execution for specified tools and requires explicit approval. Returns `FinishReason.interrupted`. + +```dart +final response = await ai.generate( + prompt: 'Delete the database.', + use: [ + // Require approval for all tools EXCEPT those below + toolApproval(approved: ['read_file', 'list_files']), + ], +); + +if (response.finishReason == FinishReason.interrupted) { + final interrupt = response.interrupts.first; + + // Ask user for approval + final isApproved = await askUser(); + + if (isApproved) { + final resumeResponse = await ai.generate( + messages: response.messages, // Pass history + toolChoice: ToolChoice.none, // Prevent immediate re-call + interruptRestart: [ + ToolRequestPart( + toolRequest: interrupt.toolRequest, + metadata: { + ...?interrupt.metadata, + 'tool-approved': true + }, + ), + ], + ); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_openai.md b/.agents/skills/developing-genkit-dart/references/genkit_openai.md new file mode 100644 index 0000000..42344db --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_openai.md @@ -0,0 +1,54 @@ +# Genkit OpenAI Plugin (`genkit_openai`) + +OpenAI-compatible API plugin for Genkit Dart. Supports OpenAI models and other compatible APIs (xAI, DeepSeek, Together AI, Groq, etc.). + +## Basic Usage + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_openai/genkit_openai.dart'; + +void main() async { + final ai = Genkit(plugins: [ + openAI(apiKey: Platform.environment['OPENAI_API_KEY']), + ]); + + final response = await ai.generate( + model: openAI.model('gpt-4o'), + prompt: 'Tell me a joke.', + ); +} +``` + +## Options + +`OpenAIOptions` allows configuring sampling temperature, nucleus sampling, token generation, seed, etc: +`config: OpenAIOptions(temperature: 0.7, maxTokens: 100)` + +## Groq API override + +Specify custom `baseUrl` and custom models to integrate with third-party providers. + +```dart +final ai = Genkit(plugins: [ + openAI( + apiKey: Platform.environment['GROQ_API_KEY'], + baseUrl: 'https://api.groq.com/openai/v1', + models: [ + CustomModelDefinition( + name: 'llama-3.3-70b-versatile', + info: ModelInfo( + label: 'Llama 3.3 70B', + supports: {'multiturn': true, 'tools': true, 'systemRole': true}, + ), + ), + ], + ), +]); + +final response = await ai.generate( + model: openAI.model('llama-3.3-70b-versatile'), + prompt: 'Hello!', +); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_shelf.md b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md new file mode 100644 index 0000000..1887f80 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md @@ -0,0 +1,59 @@ +# Genkit Shelf Plugin (`genkit_shelf`) + +Shelf integration for Genkit Dart, used to serve Genkit Flows. + +## Standalone Server +Serve Genkit Flows easily on an isolated HTTP server using `startFlowServer`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + await startFlowServer( + flows: [flow], + port: 8080, + ); +} +``` + +## Existing Shelf Application +Mount Genkit Flow endpoints directly to an existing Shelf `Router` using `shelfHandler`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as io; +import 'package:shelf_router/shelf_router.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + final router = Router(); + + // Mount the flow handler at a specific path + router.post('/myFlow', shelfHandler(flow)); + + // Start the server + await io.serve(router.call, 'localhost', 8080); +} +``` + +Access deployed flows using genkit client libraries (from Dart or JS). diff --git a/.agents/skills/developing-genkit-dart/references/schemantic.md b/.agents/skills/developing-genkit-dart/references/schemantic.md new file mode 100644 index 0000000..45939b2 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/schemantic.md @@ -0,0 +1,137 @@ +# Schemantic + +Schemantic is a general-purpose Dart library used for defining strongly typed data classes that automatically bind to reusable runtime JSON schemas. It is standard for the `genkit-dart` framework but works independently as well. + +## Core Concepts + +Always use `schemantic` when strongly typed JSON parsing or programmatic schema validation is required. + +- Annotate your abstract classes with `@Schema()`. +- Use the `$` prefix for abstract schema class names (e.g., `abstract class $User`). +- Always run `dart run build_runner build` to generate the `.g.dart` schema files. + +## Installation + +Add dependencies: + +```bash +dart pub add schemantic +``` + +## Basic Usage + +1. **Defining a schema:** + +```dart +import 'package:schemantic/schemantic.dart'; + +part 'my_file.g.dart'; // Must match the filename + +@Schema() +abstract class $MyObj { + String get name; + $MySubObj get subObj; +} + +@Schema() +abstract class $MySubObj { + String get foo; +} +``` + +2. **Using the Generated Class:** + +The builder creates a concrete class `MyObj` (no `$`) with a factory constructor (`MyObj.fromJson`) and a regular constructor. + +```dart +// Creating an instance +final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar')); + +// Serializing to JSON +print(obj.toJson()); + +// Parsing from JSON +final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}}); +``` + +3. **Accessing Schemas at Runtime:** + +The generated data classes have a static `$schema` field (of type `SchemanticType`) which can be used to pass the definition into functions or to extract the raw JSON schema. + +```dart +// Access JSON schema +final schema = MyObj.$schema.jsonSchema; +print(schema.toJson()); + +// Validate arbitrary JSON at runtime +final validationErrors = await schema.validate({'invalid': 'data'}); +``` + +## Primitive Schemas + +When a full data class is not required, Schemantic provides functions to create schemas dynamically. + +```dart +final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0); +final nameSchema = SchemanticType.string(minLength: 2); +final nothingSchema = SchemanticType.voidSchema(); +final anySchema = SchemanticType.dynamicSchema(); + +final userSchema = SchemanticType.map(.string(), .integer()); // Map +final tagsSchema = SchemanticType.list(.string()); // List +``` + +## Union Types (AnyOf) + +To allow a field to accept multiple types, use `@AnyOf`. + +```dart +@Schema() +abstract class $Poly { + @AnyOf([int, String, $MyObj]) + Object? get id; +} +``` + +Schemantic generates a specific helper class (e.g., `PolyId`) to handle the values: + +```dart +final poly1 = Poly(id: PolyId.int(123)); +final poly2 = Poly(id: PolyId.string('abc')); +``` + +## Field Annotations + +You can use specialized annotations for more validation boundaries: + +```dart +@Schema() +abstract class $User { + @IntegerField( + name: 'years_old', // Change JSON key + description: 'Age of the user', + minimum: 0, + defaultValue: 18, + ) + int? get age; + + @StringField( + minLength: 2, + enumValues: ['user', 'admin'], + ) + String get role; +} +``` + +## Recursive Schemas + +For recursive structures (like trees), must use `useRefs: true` inside the generated jsonSchema property. You define it normally: + +```dart +@Schema() +abstract class $Node { + String get id; + List<$Node>? get children; +} +``` +*Note*: `Node.$schema.jsonSchema(useRefs: true)` generates schemas with JSON Schema `$ref`. \ No newline at end of file diff --git a/.agents/skills/developing-genkit-go/SKILL.md b/.agents/skills/developing-genkit-go/SKILL.md new file mode 100644 index 0000000..5e49c35 --- /dev/null +++ b/.agents/skills/developing-genkit-go/SKILL.md @@ -0,0 +1,97 @@ +--- +name: developing-genkit-go +description: Develop AI-powered applications using Genkit in Go. Use when the user asks to build AI features, agents, flows, or tools in Go using Genkit, or when working with Genkit Go code involving generation, prompts, streaming, tool calling, or model providers. +metadata: + genkit-managed: true +--- + +# Genkit Go + +Genkit Go is an AI SDK for Go that provides generation, structured output, streaming, tool calling, prompts, and flows with a unified interface across model providers. + +## Hello World + +```go +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/genkit-ai/genkit/go/ai" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" + "github.com/genkit-ai/genkit/go/plugins/server" +) + +func main() { + ctx := context.Background() + g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) + + genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }) + + mux := http.NewServeMux() + for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) + } + log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +} +``` + +## Core Features + +Load the appropriate reference based on what you need: + +| Feature | Reference | When to load | +| --- | --- | --- | +| Initialization | [references/getting-started.md](references/getting-started.md) | Setting up `genkit.Init`, plugins, the `*Genkit` instance pattern | +| Generation | [references/generation.md](references/generation.md) | `Generate`, `GenerateText`, `GenerateData`, streaming, output formats | +| Prompts | [references/prompts.md](references/prompts.md) | `DefinePrompt`, `DefineDataPrompt`, `.prompt` files, schemas | +| Tools | [references/tools.md](references/tools.md) | `DefineTool`, tool interrupts, `RestartWith`/`RespondWith` | +| Flows & HTTP | [references/flows-and-http.md](references/flows-and-http.md) | `DefineFlow`, `DefineStreamingFlow`, `genkit.Handler`, HTTP serving | +| Model Providers | [references/providers.md](references/providers.md) | Google AI, Vertex AI, Anthropic, OpenAI-compatible, Ollama setup | + +## Genkit CLI + +Check if installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Key commands:** + +```bash +# Start app with Developer UI (tracing, flow testing) at http://localhost:4000 +genkit start -- go run . +genkit start -o -- go run . # also opens browser + +# Run a flow directly from the CLI +genkit flow:run myFlow '{"data": "input"}' +genkit flow:run myFlow '{"data": "input"}' --stream # with streaming +genkit flow:run myFlow '{"data": "input"}' --wait # wait for completion + +# Look up Genkit documentation +genkit docs:search "streaming" go +genkit docs:list go +genkit docs:read go/flows.md +``` + +See [references/getting-started.md](references/getting-started.md) for full CLI and Developer UI details. + +## Key Guidance + +- **Pass `g` explicitly.** The `*Genkit` instance returned by `genkit.Init` is the central registry. Pass it to all Genkit functions rather than storing it as a global. This is a core pattern throughout the SDK. +- **Wrap AI logic in flows.** Flows give you tracing, observability, HTTP deployment via `genkit.Handler`, and the ability to test from the Developer UI and CLI. Any generation call worth keeping should live in a flow. +- **Use `jsonschema:"description=..."` struct tags on output types.** The model uses these descriptions to understand what each field should contain. Without them, structured output quality drops significantly. +- **Write good tool descriptions.** The model decides which tools to call based on their description string. Vague descriptions lead to missed or incorrect tool calls. +- **Use `.prompt` files for complex prompts.** They separate prompt content from Go code, support Handlebars templating, and can be iterated on without recompilation. Code-defined prompts are better for simple, single-line cases. +- **Look up the latest model IDs.** Model names change frequently. Check provider documentation for current model IDs rather than relying on hardcoded names. See [references/providers.md](references/providers.md). diff --git a/.agents/skills/developing-genkit-go/references/flows-and-http.md b/.agents/skills/developing-genkit-go/references/flows-and-http.md new file mode 100644 index 0000000..92f99a2 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/flows-and-http.md @@ -0,0 +1,183 @@ +# Flows & HTTP + +## DefineFlow + +Wrap AI logic in a flow for observability, tracing, and HTTP deployment. + +```go +jokeFlow := genkit.DefineFlow(g, "jokeFlow", + func(ctx context.Context, topic string) (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), + ) + }, +) +``` + +### Running a Flow Directly + +```go +result, err := jokeFlow.Run(ctx, "cats") +``` + +## DefineStreamingFlow + +Flows that stream chunks back to the caller. Two common patterns: + +### Pattern 1: Passthrough Streaming + +Pass the stream callback directly through to `WithStreaming`. The callback type is `ai.ModelStreamCallback` = `func(context.Context, *ai.ModelResponseChunk) error`: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk ai.ModelStreamCallback) (string, error) { + resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ai.WithStreaming(sendChunk), // passthrough + ) + if err != nil { + return "", err + } + return resp.Text(), nil + }, +) +``` + +### Pattern 2: Manual String Streaming + +Use `core.StreamCallback[string]` to stream extracted text: + +```go +genkit.DefineStreamingFlow(g, "streamingJokeFlow", + func(ctx context.Context, topic string, sendChunk core.StreamCallback[string]) (string, error) { + stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long joke about %s", topic), + ) + for result, err := range stream { + if err != nil { + return "", err + } + if result.Done { + return result.Response.Text(), nil + } + sendChunk(ctx, result.Chunk.Text()) + } + return "", nil + }, +) +``` + +### Typed Streaming Flows + +Use `core.StreamCallback[T]` with `GenerateDataStream` for typed chunks: + +```go +genkit.DefineStreamingFlow(g, "structuredStream", + func(ctx context.Context, input JokeRequest, sendChunk core.StreamCallback[*Joke]) (*Joke, error) { + stream := genkit.GenerateDataStream[*Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", input.Topic), + ) + for result, err := range stream { + if err != nil { return nil, err } + if result.Done { return result.Output, nil } + sendChunk(ctx, result.Chunk) + } + return nil, nil + }, +) +``` + +## Named Sub-Steps + +Use `core.Run` inside a flow for traced sub-steps: + +```go +genkit.DefineFlow(g, "pipeline", + func(ctx context.Context, input string) (string, error) { + subject, err := core.Run(ctx, "extract-subject", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Extract the subject from: %s", input), + ) + }) + if err != nil { return "", err } + + joke, err := core.Run(ctx, "generate-joke", func() (string, error) { + return genkit.GenerateText(ctx, g, + ai.WithPrompt("Tell me a joke about %s", subject), + ) + }) + return joke, err + }, +) +``` + +## HTTP Handlers + +### genkit.Handler + +Convert any flow into an `http.HandlerFunc`: + +```go +mux := http.NewServeMux() +for _, f := range genkit.ListFlows(g) { + mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f)) +} +log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) +``` + +### Request/Response Format + +**Non-streaming request:** +```bash +curl -X POST http://localhost:8080/jokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Response: `{"result": "Why did the banana go to the doctor?..."}` + +**Streaming request:** +```bash +curl -N -X POST http://localhost:8080/streamingJokeFlow \ + -H "Content-Type: application/json" \ + -d '{"data": "bananas"}' +``` + +Streaming responses use Server-Sent Events (SSE) format. + +### genkit.HandlerFunc + +For frameworks that expect error-returning handlers: + +```go +handler := genkit.HandlerFunc(myFlow) +// handler is func(http.ResponseWriter, *http.Request) error +``` + +### Context Providers + +Inject request context (e.g., auth headers) into flow execution: + +```go +mux.HandleFunc("POST /myFlow", genkit.Handler(myFlow, + genkit.WithContextProviders(func(ctx context.Context, rd core.RequestData) (api.ActionContext, error) { + // rd.Headers contains HTTP headers + return api.ActionContext{"userId": rd.Headers.Get("X-User-Id")}, nil + }), +)) +``` + +### ListFlows + +Get all registered flows for dynamic route setup: + +```go +flows := genkit.ListFlows(g) // []api.Action +for _, f := range flows { + fmt.Println(f.Name()) +} +``` diff --git a/.agents/skills/developing-genkit-go/references/generation.md b/.agents/skills/developing-genkit-go/references/generation.md new file mode 100644 index 0000000..5934575 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/generation.md @@ -0,0 +1,176 @@ +# Generation + +## GenerateText + +Simplest form. Returns a string. + +```go +text, err := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +``` + +## Generate + +Returns a full `*ModelResponse` with metadata, usage stats, and history. + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithSystem("You are a helpful assistant."), + ai.WithPrompt("Explain %s", topic), +) +fmt.Println(resp.Text()) // concatenated text +fmt.Println(resp.FinishReason) // ai.FinishReasonStop, etc. +fmt.Println(resp.Usage) // token counts +``` + +## GenerateData (Structured Output) + +Returns a typed Go value parsed from the model's JSON output. + +```go +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup of the joke"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +joke, resp, err := genkit.GenerateData[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +// joke is *Joke, resp is *ModelResponse +``` + +## Streaming + +### GenerateStream + +Returns an iterator. Each value has `.Done`, `.Chunk`, and `.Response`. + +```go +stream := genkit.GenerateStream(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a long story about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalText := result.Response.Text() + break + } + fmt.Print(result.Chunk.Text()) // incremental text +} +``` + +### GenerateDataStream (Structured Streaming) + +Streams typed partial objects as they arrive. + +```go +stream := genkit.GenerateDataStream[Joke](ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a joke about %s", topic), +) +for result, err := range stream { + if err != nil { + return err + } + if result.Done { + finalJoke := result.Output // *Joke + break + } + partialJoke := result.Chunk // *Joke (partial) +} +``` + +### Callback-Based Streaming + +Use `ai.WithStreaming` with `Generate` for callback-style streaming. The callback receives `*ai.ModelResponseChunk`: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Tell me a story"), + ai.WithStreaming(func(ctx context.Context, chunk *ai.ModelResponseChunk) error { + fmt.Print(chunk.Text()) // extract text from chunk + return nil + }), +) +// resp contains the final complete response +``` + +## Common Options + +```go +// Model selection +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)) // model reference +ai.WithModelName("googleai/gemini-flash-latest") // by name string + +// Content +ai.WithPrompt("Tell me about %s", topic) // user message (supports fmt verbs) +ai.WithSystem("You are a pirate.") // system instructions +ai.WithMessages(msg1, msg2) // conversation history +ai.WithDocs(doc1, doc2) // context documents +ai.WithTextDocs("context 1", "context 2") // context as strings + +// Model config (provider-specific) +ai.WithConfig(map[string]any{"temperature": 0.7}) +``` + +## Output Formats + +Control how the model structures its output. + +### By Go Type + +```go +// Automatically uses JSON format and instructs model to match the type +ai.WithOutputType(MyStruct{}) +``` + +### By Format String + +```go +ai.WithOutputFormat(ai.OutputFormatJSON) // single JSON object +ai.WithOutputFormat(ai.OutputFormatJSONL) // JSON Lines (one object per line) +ai.WithOutputFormat(ai.OutputFormatArray) // JSON array +ai.WithOutputFormat(ai.OutputFormatEnum) // constrained enum value +ai.WithOutputFormat(ai.OutputFormatText) // plain text (default) +``` + +### Enum Output + +```go +type Color string +const ( + Red Color = "red" + Green Color = "green" + Blue Color = "blue" +) + +text, err := genkit.GenerateText(ctx, g, + ai.WithPrompt("What color is the sky?"), + ai.WithOutputEnums(Red, Green, Blue), +) +``` + +### Custom Output Instructions + +```go +ai.WithOutputInstructions("Return a JSON object with fields: name (string), age (number)") +``` + +### Combining Format + Schema + +```go +// JSONL with a typed schema (useful for streaming lists) +genkit.DefinePrompt(g, "characters", + ai.WithPrompt("Generate 5 story characters"), + ai.WithOutputType([]StoryCharacter{}), + ai.WithOutputFormat(ai.OutputFormatJSONL), +) +``` diff --git a/.agents/skills/developing-genkit-go/references/getting-started.md b/.agents/skills/developing-genkit-go/references/getting-started.md new file mode 100644 index 0000000..950b616 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/getting-started.md @@ -0,0 +1,142 @@ +# Getting Started + +## Project Setup + +```bash +mkdir my-genkit-app && cd my-genkit-app +go mod init my-genkit-app +go get github.com/genkit-ai/genkit/go@latest +``` + +Add provider plugin(s) for the models you want to use: +```bash +go get github.com/genkit-ai/genkit/go/plugins/googlegenai # Google AI / Vertex AI +go get github.com/genkit-ai/genkit/go/plugins/anthropic # Anthropic Claude +go get github.com/genkit-ai/genkit/go/plugins/compat_oai # OpenAI-compatible +go get github.com/genkit-ai/genkit/go/plugins/ollama # Ollama (local) +``` + +After writing your code, run `go mod tidy` to resolve all dependencies. + +## Initialization + +Every Genkit app starts with `genkit.Init`, which returns a `*Genkit` instance: + +```go +import ( + "context" + "github.com/genkit-ai/genkit/go/genkit" + "github.com/genkit-ai/genkit/go/plugins/googlegenai" +) + +ctx := context.Background() +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), +) +``` + +### The `*Genkit` Instance + +The `*Genkit` value `g` is the central registry. Pass it to every Genkit function: + +```go +// Defining resources +genkit.DefineFlow(g, "myFlow", ...) +genkit.DefineTool(g, "myTool", ...) +genkit.DefinePrompt(g, "myPrompt", ...) + +// Generating content +genkit.GenerateText(ctx, g, ...) +genkit.Generate(ctx, g, ...) +``` + +Do not store `g` in a global variable. Pass it explicitly through your call chain. + +### Init Options + +```go +g := genkit.Init(ctx, + // Register one or more plugins + genkit.WithPlugins(&googlegenai.GoogleAI{}, &anthropic.Anthropic{}), + + // Set a default model (used when no model is specified) + genkit.WithDefaultModel("googleai/gemini-flash-latest"), + + // Set directory for .prompt files (default: "prompts") + genkit.WithPromptDir("my-prompts"), + + // Or embed prompts using Go's embed package + // genkit.WithPromptFS(promptsFS), +) +``` + +### Embedding Prompts + +Use `go:embed` to bundle `.prompt` files into the binary: + +```go +//go:embed prompts +var promptsFS embed.FS + +g := genkit.Init(ctx, + genkit.WithPlugins(&googlegenai.GoogleAI{}), + genkit.WithPromptFS(promptsFS), +) +``` + +## Genkit CLI + +The Genkit CLI provides a local Developer UI for running flows, tracing executions, and inspecting model interactions. + +**Install:** +```bash +curl -sL cli.genkit.dev | bash +``` + +**Verify:** +```bash +genkit --version +``` + +### Developer UI + +Start your app with the Developer UI attached: + +```bash +genkit start -- go run . +``` + +This launches: +- Your app (with tracing enabled) +- The Developer UI at `http://localhost:4000` +- A telemetry API at `http://localhost:4033` + +Add `-o` to auto-open the UI in your browser: +```bash +genkit start -o -- go run . +``` + +The Developer UI lets you: +- Run and test flows interactively +- View traces for each generation call (inputs, outputs, latency, token usage) +- Inspect prompt rendering and tool calls +- Debug multi-step flows with per-step trace data + +### Without the CLI + +Set `GENKIT_ENV=dev` to enable the reflection API without the CLI: + +```bash +GENKIT_ENV=dev go run . +``` + +## Import Paths + +```go +import ( + "github.com/genkit-ai/genkit/go/genkit" // Core: Init, Generate*, DefineFlow, etc. + "github.com/genkit-ai/genkit/go/ai" // Types: WithModel, WithPrompt, Message, Part, etc. + "github.com/genkit-ai/genkit/go/core" // Low-level: Run (sub-steps), Flow types + "github.com/genkit-ai/genkit/go/plugins/server" // server.Start for HTTP +) +``` diff --git a/.agents/skills/developing-genkit-go/references/prompts.md b/.agents/skills/developing-genkit-go/references/prompts.md new file mode 100644 index 0000000..610d563 --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/prompts.md @@ -0,0 +1,256 @@ +# Prompts + +## DefinePrompt + +Define a reusable prompt in code with a default model and template. + +```go +jokePrompt := genkit.DefinePrompt(g, "joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithInputType(JokeRequest{Topic: "example"}), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +fmt.Println(resp.Text()) +``` + +### ExecuteStream + +```go +stream := jokePrompt.ExecuteStream(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +for result, err := range stream { + if err != nil { return err } + if result.Done { break } + fmt.Print(result.Chunk.Text()) +} +``` + +### Override Options at Execution + +```go +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), + ai.WithModelName("googleai/gemini-pro-latest"), // override model + ai.WithConfig(map[string]any{"temperature": 0.9}), + ai.WithTools(myTool), +) +``` + +## DefineDataPrompt (Typed Input/Output) + +Strongly-typed prompts with Go generics. + +```go +type JokeRequest struct { + Topic string `json:"topic"` +} + +type Joke struct { + Setup string `json:"setup" jsonschema:"description=The setup"` + Punchline string `json:"punchline" jsonschema:"description=The punchline"` +} + +jokePrompt := genkit.DefineDataPrompt[JokeRequest, *Joke](g, "structured-joke", + ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)), + ai.WithPrompt("Tell me a joke about {{topic}}."), +) +``` + +### Execute (typed) + +```go +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +// joke is *Joke, resp is *ModelResponse +``` + +### ExecuteStream (typed) + +```go +stream := jokePrompt.ExecuteStream(ctx, JokeRequest{Topic: "cats"}) +for result, err := range stream { + if err != nil { return err } + if result.Done { + finalJoke := result.Output // *Joke + break + } + fmt.Print(result.Chunk) // partial *Joke +} +``` + +## .prompt Files (Dotprompt) + +Define prompts in separate files with YAML frontmatter and Handlebars templates. + +### Basic .prompt File + +`prompts/joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string +--- +Tell me a joke about {{topic}}. +``` + +### Load and Use + +```go +// LookupPrompt returns Prompt (untyped: map[string]any input, string output) +jokePrompt := genkit.LookupPrompt(g, "joke") +resp, err := jokePrompt.Execute(ctx, + ai.WithInput(map[string]any{"topic": "cats"}), +) +``` + +### Typed .prompt File + +`prompts/structured-joke.prompt`: +``` +--- +model: googleai/gemini-flash-latest +config: + thinkingConfig: + thinkingBudget: 0 +input: + schema: JokeRequest +output: + format: json + schema: Joke +--- +Tell me a joke about {{topic}}. +``` + +Register Go types so the .prompt file can reference them by name: +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) + +jokePrompt := genkit.LookupDataPrompt[JokeRequest, *Joke](g, "structured-joke") +joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"}) +``` + +### LoadPrompt (Explicit Path) + +```go +prompt := genkit.LoadPrompt(g, "./prompts/countries.prompt", "countries") +resp, err := prompt.Execute(ctx) +``` + +### .prompt File Features + +**Multi-message prompts with roles:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + question: string +--- +{{ role "system" }} +You are a helpful assistant. + +{{ role "user" }} +{{question}} +``` + +**Media in prompts:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + videoUrl: string + contentType: string +--- +{{ role "user" }} +Summarize this video: +{{media url=videoUrl contentType=contentType}} +``` + +**Conditionals and loops:** +``` +--- +input: + schema: + topic: string + dietaryRestrictions?(array): string +--- +Write a recipe about {{topic}}. +{{#if dietaryRestrictions}} +Dietary restrictions: {{#each dietaryRestrictions}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}. +{{/if}} +``` + +**Inline schema in .prompt file:** +``` +--- +model: googleai/gemini-flash-latest +input: + schema: + topic: string + style?: string +output: + format: json + schema: + title: string + body: string + tags(array): string +--- +Write an article about {{topic}}. +{{#if style}}Write in a {{style}} style.{{/if}} +``` + +## Schemas + +### DefineSchemaFor (from Go type) + +Registers a Go struct as a named schema for use in `.prompt` files. + +```go +genkit.DefineSchemaFor[JokeRequest](g) +genkit.DefineSchemaFor[Joke](g) +``` + +The schema name matches the Go type name. Use `jsonschema` struct tags for metadata: + +```go +type Recipe struct { + Title string `json:"title" jsonschema:"description=The recipe title"` + Difficulty string `json:"difficulty" jsonschema:"enum=easy,enum=medium,enum=hard"` + Ingredients []Ingredient `json:"ingredients"` + Steps []string `json:"steps"` +} + +type Ingredient struct { + Name string `json:"name"` + Amount float64 `json:"amount"` + Unit string `json:"unit"` +} +``` + +### DefineSchema (manual JSON Schema) + +```go +genkit.DefineSchema(g, "Recipe", map[string]any{ + "type": "object", + "properties": map[string]any{ + "title": map[string]any{"type": "string"}, + "ingredients": map[string]any{ + "type": "array", + "items": map[string]any{"type": "object"}, + }, + }, + "required": []string{"title", "ingredients"}, +}) +``` diff --git a/.agents/skills/developing-genkit-go/references/providers.md b/.agents/skills/developing-genkit-go/references/providers.md new file mode 100644 index 0000000..dbf137c --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/providers.md @@ -0,0 +1,157 @@ +# Model Providers + +## Google AI (Gemini) + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{})) +``` + +**Env var:** `GEMINI_API_KEY` or `GOOGLE_API_KEY` + +Model names follow the format `googleai/`. Look up the latest model IDs at https://ai.google.dev/gemini-api/docs/models. + +```go +// By name string +ai.WithModelName("googleai/gemini-flash-latest") + +// Model ref with provider-specific config +ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", &genai.GenerateContentConfig{ + ThinkingConfig: &genai.ThinkingConfig{ + ThinkingBudget: genai.Ptr[int32](0), // disable thinking + }, +})) + +// Lookup a model instance +m := googlegenai.GoogleAIModel(g, "gemini-flash-latest") +``` + +## Vertex AI + +```go +import "github.com/genkit-ai/genkit/go/plugins/googlegenai" + +g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.VertexAI{})) +``` + +**Env vars:** `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION` (or `GOOGLE_CLOUD_REGION`) + +Uses Application Default Credentials (`gcloud auth application-default login`). + +Model names follow the format `vertexai/`. Same model IDs as Google AI. + +```go +ai.WithModelName("vertexai/gemini-flash-latest") +``` + +## Anthropic (Claude) + +```go +import ( + "github.com/anthropics/anthropic-sdk-go" // Anthropic SDK types + ant "github.com/genkit-ai/genkit/go/plugins/anthropic" // Genkit plugin +) + +g := genkit.Init(ctx, genkit.WithPlugins(&ant.Anthropic{})) +``` + +**Env var:** `ANTHROPIC_API_KEY` + +Model names follow the format `anthropic/`. Look up the latest model IDs at https://docs.anthropic.com/en/docs/about-claude/models. + +```go +// By name +ai.WithModelName("anthropic/claude-sonnet-4-6") + +// With provider-specific config (uses Anthropic SDK types via ai.WithConfig) +ai.WithConfig(&anthropic.MessageNewParams{ + Temperature: anthropic.Float(1.0), + MaxTokens: *anthropic.IntPtr(2000), + Thinking: anthropic.ThinkingConfigParamUnion{ + OfEnabled: &anthropic.ThinkingConfigEnabledParam{ + BudgetTokens: *anthropic.IntPtr(1024), + }, + }, +}) +``` + +## OpenAI-Compatible (compat_oai) + +Works with any OpenAI-compatible API: OpenAI, DeepSeek, xAI, etc. + +```go +import "github.com/genkit-ai/genkit/go/plugins/compat_oai" + +openaiPlugin := &compat_oai.OpenAICompatible{ + Provider: "openai", // unique identifier + APIKey: os.Getenv("OPENAI_API_KEY"), + // BaseURL: "https://custom-endpoint/v1", // for non-OpenAI providers +} +g := genkit.Init(ctx, genkit.WithPlugins(openaiPlugin)) +``` + +Define models explicitly (not auto-discovered): + +```go +model := openaiPlugin.DefineModel("openai", "gpt-4o", compat_oai.ModelOptions{}) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Ollama (Local Models) + +```go +import "github.com/genkit-ai/genkit/go/plugins/ollama" + +ollamaPlugin := &ollama.Ollama{ + ServerAddress: "http://localhost:11434", + Timeout: 60, // seconds +} +g := genkit.Init(ctx, genkit.WithPlugins(ollamaPlugin)) +``` + +Define models explicitly: + +```go +model := ollamaPlugin.DefineModel(g, + ollama.ModelDefinition{ + Name: "llama3.1", + Type: "chat", // or "generate" + }, + nil, // optional *ModelOptions +) +``` + +Use with: +```go +ai.WithModel(model) +``` + +## Multiple Providers + +Register multiple plugins in a single Genkit instance: + +```go +g := genkit.Init(ctx, + genkit.WithPlugins( + &googlegenai.GoogleAI{}, + &ant.Anthropic{}, + ), + genkit.WithDefaultModel("googleai/gemini-flash-latest"), +) + +// Use different models per call +text1, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("Hello from Gemini"), +) + +text2, _ := genkit.GenerateText(ctx, g, + ai.WithModelName("anthropic/claude-sonnet-4-6"), + ai.WithPrompt("Hello from Claude"), +) +``` diff --git a/.agents/skills/developing-genkit-go/references/tools.md b/.agents/skills/developing-genkit-go/references/tools.md new file mode 100644 index 0000000..d4a37de --- /dev/null +++ b/.agents/skills/developing-genkit-go/references/tools.md @@ -0,0 +1,178 @@ +# Tools + +## DefineTool + +Define a tool the model can call during generation. + +```go +type WeatherInput struct { + Location string `json:"location" jsonschema:"description=City name"` +} + +type WeatherOutput struct { + Temperature float64 `json:"temperature"` + Conditions string `json:"conditions"` +} + +weatherTool := genkit.DefineTool(g, "getWeather", + "Gets the current weather for a location.", + func(ctx *ai.ToolContext, input WeatherInput) (WeatherOutput, error) { + // Call your weather API + return WeatherOutput{Temperature: 72, Conditions: "sunny"}, nil + }, +) +``` + +## Using Tools in Generation + +Pass tools to `Generate`, `GenerateText`, or prompts: + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithPrompt("What's the weather in San Francisco?"), + ai.WithTools(weatherTool), +) +// The model calls the tool automatically and incorporates the result +fmt.Println(resp.Text()) +``` + +### Tool Choice + +```go +ai.WithToolChoice(ai.ToolChoiceAuto) // model decides (default) +ai.WithToolChoice(ai.ToolChoiceRequired) // model must use a tool +ai.WithToolChoice(ai.ToolChoiceNone) // model cannot use tools +``` + +### Max Turns + +Limit how many tool-call round trips the model can make: + +```go +ai.WithMaxTurns(3) // default is 5 +``` + +## DefineMultipartTool + +Tools that return both structured output and media content: + +```go +screenshotTool := genkit.DefineMultipartTool(g, "screenshot", + "Takes a screenshot of the current page", + func(ctx *ai.ToolContext, input any) (*ai.MultipartToolResponse, error) { + return &ai.MultipartToolResponse{ + Output: map[string]any{"success": true}, + Content: []*ai.Part{ai.NewMediaPart("image/png", base64Data)}, + }, nil + }, +) +``` + +## Tool Interrupts + +Pause tool execution to request human input before continuing. + +### Interrupting + +```go +type TransferInput struct { + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` +} + +type TransferOutput struct { + Status string `json:"status"` + Message string `json:"message"` + Balance float64 `json:"balance"` +} + +type TransferInterrupt struct { + Reason string `json:"reason"` + ToAccount string `json:"toAccount"` + Amount float64 `json:"amount"` + Balance float64 `json:"balance"` +} + +transferTool := genkit.DefineTool(g, "transferMoney", + "Transfers money to another account.", + func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if input.Amount > accountBalance { + return TransferOutput{}, ai.InterruptWith(ctx, TransferInterrupt{ + Reason: "insufficient_balance", + ToAccount: input.ToAccount, + Amount: input.Amount, + Balance: accountBalance, + }) + } + // Process transfer... + return TransferOutput{Status: "success", Balance: newBalance}, nil + }, +) +``` + +### Handling Interrupts + +```go +resp, err := genkit.Generate(ctx, g, + ai.WithModelName("googleai/gemini-flash-latest"), + ai.WithTools(transferTool), + ai.WithPrompt(userRequest), +) + +for resp.FinishReason == ai.FinishReasonInterrupted { + var restarts, responses []*ai.Part + + for _, interrupt := range resp.Interrupts() { + meta, ok := ai.InterruptAs[TransferInterrupt](interrupt) + if !ok { + continue + } + + switch meta.Reason { + case "insufficient_balance": + // RestartWith: re-execute the tool with adjusted input + part, err := transferTool.RestartWith(interrupt, + ai.WithNewInput(TransferInput{ + ToAccount: meta.ToAccount, + Amount: meta.Balance, // transfer what's available + }), + ) + if err != nil { return err } + restarts = append(restarts, part) + + case "confirm_large": + // RespondWith: provide a response directly without re-executing + part, err := transferTool.RespondWith(interrupt, + TransferOutput{Status: "cancelled", Message: "User declined"}, + ) + if err != nil { return err } + responses = append(responses, part) + } + } + + // Continue generation with the resolved interrupts + resp, err = genkit.Generate(ctx, g, + ai.WithMessages(resp.History()...), + ai.WithTools(transferTool), + ai.WithToolRestarts(restarts...), + ai.WithToolResponses(responses...), + ) + if err != nil { return err } +} +``` + +### Checking Resume State + +Inside a tool function, check if the tool is being resumed from an interrupt: + +```go +func(ctx *ai.ToolContext, input TransferInput) (TransferOutput, error) { + if ctx.IsResumed() { + // This is a resumed call after an interrupt + original, ok := ai.OriginalInputAs[TransferInput](ctx) + // original contains the input from the first call + } + // ... +} +``` diff --git a/.agents/skills/developing-genkit-js/SKILL.md b/.agents/skills/developing-genkit-js/SKILL.md new file mode 100644 index 0000000..d8e1e76 --- /dev/null +++ b/.agents/skills/developing-genkit-js/SKILL.md @@ -0,0 +1,112 @@ +--- +name: developing-genkit-js +description: Develop AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems. +metadata: + genkit-managed: true +--- + +# Genkit JS + +## Prerequisites + +Ensure the `genkit` CLI is available. +- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0** +- If not found or if an older version (1.x < 1.29.0) is present, install/upgrade it: `npm install -g genkit-cli@^1.29.0`. + +**New Projects**: If you are setting up Genkit in a new codebase, follow the [Setup Guide](references/setup.md). + +## Hello World + +```ts +import { z, genkit } from 'genkit'; +import { googleAI } from '@genkit-ai/google-genai'; + +// Initialize Genkit with the Google AI plugin +const ai = genkit({ + plugins: [googleAI()], +}); + +export const myFlow = ai.defineFlow({ + name: 'myFlow', + inputSchema: z.string().default('AI'), + outputSchema: z.string(), +}, async (subject) => { + const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: `Tell me a joke about ${subject}`, + }); + return response.text; +}); +``` + +## Critical: Do Not Trust Internal Knowledge + +Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended: + +```sh +genkit docs:read js/get-started.md +genkit docs:read js/flows.md +``` + +See [Common Errors](references/common-errors.md) for a list of deprecated APIs (e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x replacements. + +**ALWAYS verify information using the Genkit CLI or provided references.** + +## Error Troubleshooting Protocol + +**When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):** + +1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md) +2. Identify if the error matches a known pattern +3. Apply the documented solution +4. Only if not found in common-errors.md, then consult other sources (e.g. `genkit docs:search`) + +**DO NOT:** +- Attempt fixes based on assumptions or internal knowledge +- Skip reading common-errors.md "because you think you know the fix" +- Rely on patterns from pre-1.0 Genkit + +**This protocol is non-negotiable for error handling.** + +## Development Workflow + +1. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.). + - If the user does not specify a provider, default to **Google AI**. + - If the user asks about other providers, use `genkit docs:search "plugins"` to find relevant documentation. +2. **Detect Framework**: Check `package.json` to identify the runtime (Next.js, Firebase, Express). + - Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or `@genkit-ai/google-cloud`. + - Adapt implementation to the specific framework's patterns. +3. **Follow Best Practices**: + - See [Best Practices](references/best-practices.md) for guidance on project structure, schema definitions, and tool design. + - **Be Minimal**: Only specify options that differ from defaults. When unsure, check docs/source. +4. **Ensure Correctness**: + - Run type checks (e.g., `npx tsc --noEmit`) after making changes. + - If type checks fail, consult [Common Errors](references/common-errors.md) before searching source code. +5. **Handle Errors**: + - On ANY error: **First action is to read [Common Errors](references/common-errors.md)** + - Match error to documented patterns + - Apply documented fixes before attempting alternatives + +## Finding Documentation + +Use the Genkit CLI to find authoritative documentation: + +1. **Search topics**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` +2. **List all docs**: `genkit docs:list` +3. **Read a guide**: `genkit docs:read ` + - Example: `genkit docs:read js/flows.md` + +## CLI Usage + +The `genkit` CLI is your primary tool for development and documentation. +- See [CLI Reference](references/docs-and-cli.md) for common tasks, workflows, and command usage. +- Use `genkit --help` for a full list of commands. + +## References + +- [Best Practices](references/best-practices.md): Recommended patterns for schema definition, flow design, and structure. +- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search, CLI tasks, and workflows. +- [Common Errors](references/common-errors.md): Critical "gotchas", migration guide, and troubleshooting. +- [Setup Guide](references/setup.md): Manual setup instructions for new projects. +- [Examples](references/examples.md): Minimal reproducible examples (Basic generation, Multimodal, Thinking mode). diff --git a/.agents/skills/developing-genkit-js/references/best-practices.md b/.agents/skills/developing-genkit-js/references/best-practices.md new file mode 100644 index 0000000..f6e4b7b --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/best-practices.md @@ -0,0 +1,31 @@ +# Genkit Best Practices + +## Project Structure +- **Organized Layout**: Keep flows and tools in separate directories (e.g., `src/flows`, `src/tools`) to maintain a clean codebase. +- **Index Exports**: Use `index.ts` files to export flows and tools, making it easier to import them into your main configuration. + +## Model Selection (Google AI) +- **Gemini Models**: If using Google AI, ALWAYS use the latest generation (`gemini-3-*` or `gemini-2.5-*`). + - **NEVER** use `gemini-2.0-*` or `gemini-1.5-*` series, as they are decommissioned and won't work. + - **Recommended**: `gemini-2.5-flash` or `gemini-3-flash-preview` for general use, `gemini-3.1-pro-preview` for complex tasks. + +## Model Selection (Other Providers) +- **Consult Documentation**: For other providers (OpenAI, Anthropic, etc.), refer to the provider's official documentation for the latest recommended model versions. + +## Schema Definition +- **Use `z` from `genkit`**: Always import `z` from the `genkit` package to ensure compatibility. + ```ts + import { z } from "genkit"; + ``` +- **Descriptive Schemas**: Use `.describe()` on Zod fields. LLMs use these descriptions to understand how to populate the fields. + +## Flow & Tool Design +- **Modularize**: Keep flows and tools in separate files/modules and import them into your main Genkit configuration. +- **Single Responsibility**: Tools should do one thing well. Complex logic should be broken down. + +## Configuration +- **Environment Variables**: Store sensitive keys (like API keys) in environment variables or `.env` files. Do not hardcode them. + +## Development +- **Use Dev Mode**: Run your app with `genkit start -- ` to enable the Developer UI. +- It is recommended to configure a watcher to auto-reload your app (e.g. `node --watch` or `tsx --watch`) diff --git a/.agents/skills/developing-genkit-js/references/common-errors.md b/.agents/skills/developing-genkit-js/references/common-errors.md new file mode 100644 index 0000000..d7162e6 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/common-errors.md @@ -0,0 +1,132 @@ +# Common Errors & Pitfalls + +## When Typecheck Fails + +**Before searching source code or docs**, check the sections below. Many type errors are caused by deprecated APIs or incorrect imports. + +## Genkit v1.x vs Pre-1.0 Migration + +Genkit v1.x introduced significant API changes. This section covers critical syntax updates. + +### Package Imports + +- **Correct (v1.x)**: Import core functionality (zod, genkit) from the main `genkit` package and plugins from their specific packages. + ```ts + import { z, genkit } from 'genkit'; + import { googleAI } from '@genkit-ai/google-genai'; + ``` + +- **Incorrect (Pre-1.0)**: Importing from `@genkit-ai/ai`, `@genkit-ai/core`, or `@genkit-ai/flow`. These packages are internal/deprecated for direct use. + ```ts + import { genkit } from "@genkit-ai/core"; // INCORRECT + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + ``` + +### Model References + +- **Correct**: Use plugin-specific model factories or string identifiers (prefaced by plugin name). + ```ts + // Using model factory (v1.x - Preferred) + await ai.generate({ model: googleAI.model('gemini-2.5-flash'), ... }); + + // Using string identifier + await ai.generate({ model: 'googleai/gemini-2.5-flash', ...}); + // Or + await ai.generate({ model: 'vertexai/gemini-2.5-flash', ...}); + ``` +- **Incorrect**: Using imported model objects directly or string identifiers without plugin name. + ```ts + await ai.generate({ model: gemini15Pro, ... }); // INCORRECT (Pre-1.0) + await ai.generate({ model: 'gemini-2.5-flash', ... }); // INCORRECT (No plugin prefix) + ``` + +### Model Selection (Gemini) + +- **Preferred**: Use `gemini-2.5-*` models for best performance and features. + ```ts + model: googleAI.model('gemini-2.5-flash') // PREFERRED + ``` +- **DEPRECATED**: `gemini-1.5-*` models are deprecated and will throw errors. + ```ts + model: googleAI.model('gemini-1.5-flash') // ERROR (Deprecated) + ``` + +### Response Access + +- **Correct (v1.x)**: Access properties directly. + ```ts + response.text; // CORRECT + response.output; // CORRECT + ``` +- **Incorrect (Pre-1.0)**: Calling as methods. + ```ts + response.text(); // INCORRECT + response.output(); // INCORRECT + ``` + +### Streaming Generation + +- **Correct (v1.x)**: Do NOT await `generateStream`. Iterate over `stream` directly. Await `response` property for final result. + ```ts + const {stream, response} = ai.generateStream(...); // NO await here + for await (const chunk of stream) { ... } // Iterate stream + const finalResponse = await response; // Await response property + ``` +- **Incorrect (Pre-1.0)**: Calling stream as a function or awaiting the generator incorrectly. + ```ts + for await (const chunk of stream()) { ... } // INCORRECT + await response(); // INCORRECT + ``` + +### Initialization + +- **Correct (v1.x)**: Instantiate `genkit`. + ```ts + const ai = genkit({ plugins: [...] }); + ``` +- **Incorrect (Pre-1.0)**: Global configuration. + ```ts + configureGenkit({ plugins: [...] }); // INCORRECT + ``` + +### Flow Definitions + +- **Correct (v1.x)**: Define flows on the `ai` instance. + ```ts + ai.defineFlow({...}, (input) => {...}); + ``` +- **Incorrect (Pre-1.0)**: Importing `defineFlow` globally. + ```ts + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + +You should never import `@genkit-ai/flow`, `@genkit-ai/ai` or `@genkit-ai/core` packages directly. + +## Zod & Schema Errors + +- **Import Source**: ALWAYS use `import { z } from "genkit"`. + - Using `zod` directly from `zod` package may cause instance mismatches or compatibility issues. +- **Supported Types**: Stick to basic types: scalar (`string`, `number`, `boolean`), `object`, and `array`. + - Avoid complex Zod features unless strictly necessary and verified. +- **Descriptions**: Always use `.describe('...')` for fields in output schemas to guide the LLM. + +## Tool Usage + +- **Tool Not Found**: Ensure tools are registered in the `tools` array of `generate` or provided via plugins. +- **MCP Tools**: Use the `ServerName:tool_name` format when referencing MCP tools. + +## Multimodal & Image Generation + +- **Missing responseModalities**: When using image generation models (like `gemini-2.5-flash-image`), you **MUST** specify the response modalities in the config. + ```ts + config: { + responseModalities: ["TEXT", "IMAGE"] + } + ``` + Failure to do so will result in errors or incorrect output format. + +## Audio & Speech Generation + +- **Raw PCM Data vs MP3**: Some providers (e.g., Google GenAI) return raw PCM data, while others (e.g., OpenAI) return MP3. + - **DO NOT assume MP3 format.** + - **DO NOT embed raw PCM in HTML audio tags.** + - **Action**: Run `genkit docs:search "speech audio"` to find provider-specific conversion steps (e.g., PCM to WAV). diff --git a/.agents/skills/developing-genkit-js/references/docs-and-cli.md b/.agents/skills/developing-genkit-js/references/docs-and-cli.md new file mode 100644 index 0000000..3561721 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/docs-and-cli.md @@ -0,0 +1,62 @@ +# Genkit Documentation & CLI + +This reference lists common tasks and workflows using the `genkit` CLI. For authoritative command details, always run `genkit --help` or `genkit --help`. + +## Prerequisites: + +Ensure that the CLI is on `genkit-cli` version >= 1.29.0. If not, or if an older version (1.x < 1.29.0) is present, update the Genkit CLI version. Alternatively, to run commands with a specific version or without global installation, prefix them with `npx -y genkit-cli@^1.29.0`. + +## Documentation + +- **Search docs**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` + - Example: `genkit docs:search "rag retrieval"` +- **Read doc**: `genkit docs:read ` + - Example: `genkit docs:read js/overview.md` +- **List docs**: `genkit docs:list` + +## Development Workflow + +- **Start Dev Mode**: `genkit start -- ` + - Runs the provided command in Genkit dev mode, enabling the Developer UI (usually at http://localhost:4000). + - **Node.js (TypeScript)**: + ```bash + genkit start -- npx tsx --watch src/index.ts + ``` + - **Next.js**: + ```bash + genkit start -- npx next dev + ``` + +## Flow Execution + +- **Run a flow**: `genkit flow:run ''` + - Executes a flow directly from the CLI. Useful for testing. + - **Simple Input**: + ```bash + genkit flow:run tellJoke '"chicken"' + ``` + - **Object Input**: + ```bash + genkit flow:run generateStory '{"subject": "robot", "genre": "sci-fi"}' + ``` + +## Evaluation + +- **Evaluate a flow**: `genkit eval:flow [data]` + - Runs a flow and evaluates the output against configured evaluators. + - **Example (Single Input)**: + ```bash + genkit eval:flow answerQuestion '[{"testCaseId": "1", "input": {"question": "What is Genkit?"}}]' + ``` + - **Example (Batch Input)**: + ```bash + genkit eval:flow answerQuestion --input inputs.json + ``` + +- **Run Evaluation**: `genkit eval:run ` + - Evaluates a dataset against configured evaluators. + - **Example**: + ```bash + genkit eval:run dataset.json --output results.json + ``` \ No newline at end of file diff --git a/.agents/skills/developing-genkit-js/references/examples.md b/.agents/skills/developing-genkit-js/references/examples.md new file mode 100644 index 0000000..2279b4e --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/examples.md @@ -0,0 +1,157 @@ +# Genkit Examples + +This reference contains minimal, reproducible examples (MREs) for common Genkit patterns. + +> **Disclaimer**: These examples use **Google AI** models (`googleAI`, `gemini-*`) for demonstration. The patterns apply to **any provider**. To use a different provider: +> 1. Search the docs for the correct plugin: `genkit docs:search "plugins"`. +> 2. Install and configure the plugin. +> 3. Swap the model reference in the code. + +## Basic Text Generation + +```ts +import { genkit } from "genkit"; +import { googleAI } from "@genkit-ai/google-genai"; + +const ai = genkit({ + plugins: [googleAI()], +}); + +const { text } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a story in a pirate accent', +}); +``` + +## Structured Output + +```ts +import { z } from 'genkit'; + +const JokeSchema = z.object({ + setup: z.string().describe('The setup of the joke'), + punchline: z.string().describe('The punchline'), +}); + +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a joke about developers.', + output: { schema: JokeSchema }, +}); + +// response.output is strongly typed +const joke = response.output; +if (joke) { + console.log(`${joke.setup} ... ${joke.punchline}`); +} +``` + +## Streaming + +```ts +const { stream, response } = ai.generateStream({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell a long story about a developer using Genkit.', +}); + +for await (const chunk of stream) { + console.log(chunk.text); +} + +// Await the final response +const finalResponse = await response; +console.log('Complete:', finalResponse.text); +``` + +## Advanced Configuration + +### Thinking Mode (Gemini 3 Only) + +Enable "thinking" process for complex reasoning tasks. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-3.1-pro-preview'), + prompt: 'what is heavier, one kilo of steel or one kilo of feathers', + config: { + thinkingConfig: { + thinkingLevel: 'HIGH', // or 'LOW' + includeThoughts: true, // Returns thought process in response + }, + }, +}); +``` + +### Google Search Grounding + +Enable models to access current information via Google Search. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'What are the top tech news stories this week?', + config: { + googleSearchRetrieval: true, + }, +}); + +// Access grounding metadata (sources) +const groundingMetadata = (response.custom as any)?.candidates?.[0]?.groundingMetadata; +if (groundingMetadata) { + console.log('Sources:', groundingMetadata.groundingChunks); +} +``` + +## Multimodal Generation + +### Image Generation / Editing + +**Critical**: You MUST set `responseModalities: ['TEXT', 'IMAGE']` when using image generation models. + +```ts +// Generate an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: "generate a picture of a unicorn wearing a space suit on the moon", +}); +// media.url contains the data URI +``` + +```ts +// Edit an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: [ + { text: "change the person's outfit to a banana costume" }, + { media: { url: "https://example.com/photo.jpg" } }, + ], +}); +``` + +### Speech Generation (TTS) + +Generate audio from text. + +```ts +import { writeFile } from 'node:fs/promises'; + +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-preview-tts'), + config: { + responseModalities: ['AUDIO'], + speechConfig: { + voiceConfig: { + prebuiltVoiceConfig: { voiceName: 'Algenib' }, // Options: 'Puck', 'Charon', 'Fenrir', etc. + }, + }, + }, + prompt: 'Genkit is an amazing library', +}); + +// The response contains raw PCM data in media.url (base64 encoded). +// CAUTION: This is NOT an MP3/WAV file. It requires conversion (e.g., PCM to WAV). +// DO NOT GUESS. Run `genkit docs:search "speech audio"` to find the correct +// conversion code for your provider. +``` diff --git a/.agents/skills/developing-genkit-js/references/setup.md b/.agents/skills/developing-genkit-js/references/setup.md new file mode 100644 index 0000000..dcbc8bd --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/setup.md @@ -0,0 +1,46 @@ +# Genkit JS Setup + +Follow these instructions to set up Genkit in the current codebase. These instructions are general-purpose and have not been written with specific codebase knowledge, so use your best judgement when following them. + +0. Tell the user "I'm going to check out your workspace and set you up to use Genkit for GenAI workflows." +1. If the current workspace is empty or is a starter template, your goal will be to create a simple image generation flow that allows someone to generate an image based on a prompt and selectable style. If the current workspace is not empty, you will create a simple example flow to help get the user started. +2. Check to see if any Genkit provider plugin (such as `@genkit-ai/google-genai` or `@genkit-ai/oai-compat` or others, may start with `genkitx-*`) is installed. + - If not, ask the user which provider they want to use. + - **For non-Google providers**: Use `genkit docs:search "plugins"` to find the correct package and installation instructions. + - If they have no preference, default to `@genkit-ai/google-genai` for a quick start. + - If this is a Next.js app, install `@genkit-ai/next` as well. +3. Search the codebase for the exact string `genkit(` (remember to escape regexes properly) which would indicate that the user has already set up Genkit in the codebase. If found, no need to set it up again, tell the user "Genkit is already configured in this app." and exit this workflow. +4. Create an `ai` directory in the primary source directory of the project (this may be e.g. `src` but is project-dependent). Adapt this path if your project uses a different structure. +5. Create `{sourceDir}/ai/genkit.ts` and populate it using the example below. DO NOT add a `next` plugin to the file, ONLY add a model provider plugin to the plugins array: + +```ts +import { genkit, z } from 'genkit'; +// Import your chosen provider plugin here. Example: +import { googleAI } from '@genkit-ai/google-genai'; + +export const ai = genkit({ + plugins: [ + googleAI(), // Add your provider plugin here + ], + model: googleAI.model('gemini-2.5-flash'), // Set your provider's model here +}); + +export { z }; +``` + +6. Create `{sourceDir}/ai/tools` and `{sourceDir}/ai/flows` directories, but leave them empty for now. +7. Create `{sourceDir}/ai/index.ts` and populate it with the following (change the import to match import aliases in `tsconfig.json` as needed): + +```ts +import './genkit.js'; +// import each created flow, tool, etc. here for use in the Genkit Dev UI +``` + +8. Add a `genkit:ui` script to `package.json` that runs `genkit start -- npx tsx --watch {sourceDir}/ai/index.ts` (or `npx genkit-cli` or `pnpm dlx` or `yarn dlx` for those package managers, if CLI is not locally installed). DO NOT try to run the script now. +9. Tell the user "Genkit is now configured and ready for use." as setup is now complete. Also remind them to set appropriate env variables (e.g. `GEMINI_API_KEY` for Google providers). Wait for the user to prompt further before creating any specific flows. + +## Next Steps & Troubleshooting + +- **Documentation**: Use the [CLI](docs-and-cli.md) to access documentation (e.g., `genkit docs:search`). +- **Building Flows**: See [examples.md](examples.md) for patterns on creating flows, adding tools, and advanced configuration. +- **Troubleshooting**: If you encounter issues during setup or initialization, check [common-errors.md](common-errors.md) for solutions. diff --git a/.agents/skills/firebase-ai-logic/SKILL.md b/.agents/skills/firebase-ai-logic/SKILL.md new file mode 100644 index 0000000..f7ec367 --- /dev/null +++ b/.agents/skills/firebase-ai-logic/SKILL.md @@ -0,0 +1,109 @@ +--- +name: firebase-ai-logic +description: Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security. +version: 1.0.0 +--- + +# Firebase AI Logic Basics + +## Overview + +Firebase AI Logic is a product of Firebase that allows developers to add gen AI to their mobile and web apps using client-side SDKs. You can call Gemini models directly from your app without managing a dedicated backend. Firebase AI Logic, which was previously known as "Vertex AI for Firebase", represents the evolution of Google's AI integration platform for mobile and web developers. + +It supports the two Gemini API providers: +- **Gemini Developer API**: It has a free tier ideal for prototyping, and pay-as-you-go for production +- **Vertex AI Gemini API**: Ideal for scale with enterprise-grade production readiness, requires Blaze plan + +Use the Gemini Developer API as a default, and only Vertex AI Gemini API if the application requires it. + +## Setup & Initialization + +### Prerequisites + +- Before starting, ensure you have **Node.js 16+** and npm installed. Install them if they aren’t already available. +- Identify the platform the user is interested in building on prior to starting: Android, iOS, Flutter or Web. +- If their platform is unsupported, Direct the user to Firebase Docs to learn how to set up AI Logic for their application (share this link with the user https://firebase.google.com/docs/ai-logic/get-started) + +### Installation + +The library is part of the standard Firebase Web SDK. + +`npm install -g firebase@latest` + +If you're in a firebase directory (with a firebase.json) the currently selected project will be marked with "current" using this command: + +`npx -y firebase-tools@latest projects:list` + +Ensure there's at least one app associated with the current project + +`npx -y firebase-tools@latest apps:list` + +Initialize AI logic SDK with the init command + +`npx -y firebase-tools@latest init # Choose AI logic` + +This will automatically enable the Gemini Developer API in the Firebase console. + +More info in [Firebase AI Logic Getting Started](https://firebase.google.com/docs/ai-logic/get-started.md.txt) + +## Core Capabilities + +### Text-Only Generation + +### Multimodal (Text + Images/Audio/Video/PDF input) + +Firebase AI Logic allows Gemini models to analyze image files directly from your app. This enables features like creating captions, answering questions about images, detecting objects, and categorizing images. Beyond images, Gemini can analyze other media types like audio, video, and PDFs by passing them as inline data with their MIME type. For files larger than 20 megabytes (which can cause HTTP 413 errors as inline data), store them in Cloud Storage for Firebase and pass their URLs to the Gemini Developer API. + +### Chat Session (Multi-turn) + +Maintain history automatically using `startChat`. + +### Streaming Responses + +To improve the user experience by showing partial results as they arrive (like a typing effect), use `generateContentStream` instead of `generateContent` for faster display of results. + +### Generate Images with Nano Banana + +- Start with Gemini for most use cases, and choose Imagen for specialized tasks where image quality and specific styles are critical. (Example: gemini-2.5-flash-image) +- Requires an upgraded Blaze pay-as-you-go billing plan. + +### Search Grounding with the built in googleSearch tool + +## Supported Platforms and Frameworks + +Supported Platforms and Frameworks include Kotlin and Java for Android, Swift for iOS, JavaScript for web apps, Dart for Flutter, and C Sharp for Unity. + +## Advanced Features + +### Structured Output (JSON) + +Enforce a specific JSON schema for the response. + +### On-Device AI (Hybrid) + +Hybrid on-device inference for web apps, where the Firebase Javascript SDK automatically checks for Gemini Nano's availability (after installation) and switches between on-device or cloud-hosted prompt execution. This requires specific steps to enable model usage in the Chrome browser, more info in the [hybrid-on-device-inference documentation](https://firebase.google.com/docs/ai-logic/hybrid-on-device-inference.md.txt). + +## Security & Production + +### App Check + +Recommended: The developer must enable Firebase App Check to prevent unauthorized clients from using their API quota. see [App-check recaptcha enterprise](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider.md.txt). + +### Remote Config + +Consider that you do not need to hardcode model names (e.g., `gemini-flash-lite-latest`). Use Firebase Remote Config to update model versions dynamically without deploying new client code. See [Changing model names remotely](https://firebase.google.com/docs/ai-logic/change-model-name-remotely.md.txt) + +## Initialization Code References + +| Language, Framework, Platform | Gemini API provider | Context URL | +| :---- | :---- | :---- | +| Web Modular API | Gemini Developer API (Developer API) | firebase://docs/ai-logic/get-started | + +**Always use the most recent version of Gemini (gemini-flash-latest) unless another model is requested by the docs or the user. DO NOT USE gemini-1.5-flash** + +## References + +[Web SDK code examples and usage patterns](references/usage_patterns_web.md) + + + diff --git a/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md new file mode 100644 index 0000000..e6435bb --- /dev/null +++ b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md @@ -0,0 +1,174 @@ +# Firebase AI Logic Basics + +## Initialization Pattern +You must initialize the ai-logic service after the main Firebase App. +```JavaScript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; + + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // ... your firebase config +}; + +const app = initializeApp(firebaseConfig); + +// Initialize the AI Logic service (defaults to Gemini Developer API) +// To set the AI provider, set the backend as the second parameter +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +const generationConfig = { + candidate_count: 1, + maxOutputTokens: 2048, + stopSequences: [], + temperature: 0.7, // Balanced: creative but focused + topP: 0.95, // Standard: allows a wide range of probable tokens + topK: 40, // Standard: considers the top 40 tokens +}; + +// Specify the config as part of creating the `GenerativeModel` instance +const model = getGenerativeModel(ai, { model: "gemini-2.5-flash-lite", generationConfig }); +``` + +## Core Capabilities +Text-Only Generation +```JavaScript +async function generateText(prompt) { + const result = await model.generateContent(prompt); + const response = await result.response; + return response.text(); +} +``` + +## Multimodal (Text + Images/Audio/Video/PDF input) +Firebase AI Logic accepts Base64 encoded data or specific file references. +```JavaScript +// Helper to convert file to base64 generic object +async function fileToGenerativePart(file) { + const base64EncodedDataPromise = new Promise((resolve) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result.split(',')[1]); + reader.readAsDataURL(file); + }); + + return { + inlineData: { + data: await base64EncodedDataPromise, + mimeType: file.type, + }, + }; +} + +async function analyzeImage(prompt, imageFile) { + const imagePart = await fileToGenerativePart(imageFile); + const result = await model.generateContent([prompt, imagePart]); + return result.response.text(); +} +``` + +## Chat Session (Multi-turn) +Maintain history automatically using startChat. +```JavaScript +const chat = model.startChat({ + history: [ + { + role: "user", + parts: [{ text: "Hello, I am a developer." }], + }, + { + role: "model", + parts: [{ text: "Great to meet you. How can I help with code?" }], + }, + ], +}); + +async function sendMessage(msg) { + const result = await chat.sendMessage(msg); + return result.response.text(); +} +``` + +## Streaming Responses +For real-time UI updates (like a typing effect). +```JavaScript +async function streamResponse(prompt) { + const result = await model.generateContentStream(prompt); + for await (const chunk of result.stream) { + const chunkText = chunk.text(); + console.log("Stream chunk:", chunkText); + // Update UI here + } +} +``` + +Generate Images with Nano Banana + +```Javascript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai"; + + +// Initialize FirebaseApp +const firebaseApp = initializeApp(firebaseConfig); + +// Initialize the Gemini Developer API backend service +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +// Create a `GenerativeModel` instance with a model that supports your use case +const model = getGenerativeModel(ai, { + model: "gemini-2.5-flash-image", + // Configure the model to respond with text and images (required) + generationConfig: { + responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE], + }, +}); + +// Provide a text prompt instructing the model to generate an image +const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.'; + +// To generate an image, call `generateContent` with the text input +const result = model.generateContent(prompt); + +// Handle the generated image +try { + const inlineDataParts = result.response.inlineDataParts(); + if (inlineDataParts?.[0]) { + const image = inlineDataParts[0].inlineData; + console.log(image.mimeType, image.data); + } +} catch (err) { + console.error('Prompt or candidate was blocked:', err); +} +``` + +## Advanced Features +Structured Output (JSON) +Enforce a specific JSON schema for the response. +```JavaScript +import { getGenerativeModel, Schema } from "firebase/ai"; +const jsonModel = getGenerativeModel(ai, { + model: "gemini-2.5-flash-lite", + generationConfig: { + responseMimeType: "application/json", + // Optional: Define a schema + schema = Schema.object({ ... }); + } +}); + +async function getJsonData(prompt) { + const result = await jsonModel.generateContent(prompt); + return JSON.parse(result.response.text()); +} +``` + +On-Device AI (Hybrid) +Automatically switch between local Gemini Nano and cloud models based on device capability. +```JavaScript +import {getGenerativeModel, InferenceMode } from "firebase/ai"; + +const hybridModel = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE }); +``` + diff --git a/.agents/skills/firebase-app-hosting-basics/SKILL.md b/.agents/skills/firebase-app-hosting-basics/SKILL.md new file mode 100644 index 0000000..4aa23b7 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/SKILL.md @@ -0,0 +1,58 @@ +--- +name: firebase-app-hosting-basics +description: Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends. +--- + +# App Hosting Basics + +## Description +This skill enables the agent to deploy and manage modern, full-stack web applications (Next.js, Angular, etc.) using Firebase App Hosting. + +**Important**: In order to use App Hosting, your Firebase project must be on the Blaze pricing plan. Direct the user to https://console.firebase.google.com/project/_/overview?purchaseBillingPlan=metered to upgrade their plan. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Deploying to App Hosting + +### Deploy from Source + +This is the recommended flow for most users. +1. Configure `firebase.json` with an `apphosting` block. + ```json + { + "apphosting": { + "backendId": "my-app-id", + "rootDir": "/", + "ignore": [ + "node_modules", + ".git", + "firebase-debug.log", + "firebase-debug.*.log", + "functions" + ] + } + } + ``` +2. Create or edit `apphosting.yaml`- see [Configuration](references/configuration.md) for more information on how to do so. +3. If the app needs safe access to sensitive keys, use `npx -y firebase-tools@latest apphosting:secrets` commands to set and grant access to secrets. +4. Run `npx -y firebase-tools@latest deploy` when you are ready to deploy. + +### Automated deployment via GitHub (CI/CD) + +Alternatively, set up a backend connected to a GitHub repository for automated deployments "git push" deployments. +This is only recommended for more advanced users, and is not required to use App Hosting. +See [CLI Commands](references/cli_commands.md) for more information on how to set this up using CLI commands. + +## Emulation + +See [Emulation](references/emulation.md) for more information on how to test your app locally using the Firebase Local Emulator Suite. diff --git a/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md new file mode 100644 index 0000000..c758c9d --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md @@ -0,0 +1,71 @@ +# App Hosting CLI Commands + +The Firebase CLI provides a comprehensive suite of commands to manage App Hosting resources. These commands are often faster and more scriptable than using the Firebase Console. + +## Initialization + +### `npx -y firebase-tools@latest init apphosting` + +- **Purpose**: Interactive command that sets up App Hosting in your local project. +Use this command only if you are able to handle interactive CLI inputs well. +Alternatively, you can manually edit `firebase.json` and `apphosting.yml`. + +- **Effect**: + - Detects your web framework. + - Creates/updates `apphosting.yaml`. + - Can optionally create a backend if one doesn't exist. + +## Backend Management + +### `npx -y firebase-tools@latest apphosting:backends:list` + +- **Purpose**: Lists all backends in the current project. + +### `npx -y firebase-tools@latest apphosting:backends:get ` + +- **Purpose**: Shows details for a specific backend. + +### `npx -y firebase-tools@latest apphosting:backends:delete ` + +- **Purpose**: Deletes a backend and its associated resources. + +### `npx -y firebase-tools@latest apphosting:rollouts:list ` + +- **Purpose**: Lists the history of rollouts for a backend. + +## Secrets Management + +App Hosting uses Cloud Secret Manager to securely handle sensitive environment variables (like API keys). + +### `npx -y firebase-tools@latest apphosting:secrets:set ` + +- **Purpose**: Creates or updates a secret in Cloud Secret Manager and makes it available to App Hosting. +- **Behavior**: Prompts for the secret value (hidden input). + +### `npx -y firebase-tools@latest apphosting:secrets:grantaccess ` + +- **Purpose**: Grants the App Hosting service account permission to access the secret. +- **Note**: Often handled automatically by `secrets:set`, but useful for debugging permission issues or granting access to existing secrets. + +## Automated deployment via GitHub (CI/CD) + +**IMPORTANT** Only use these commands if you are setting up automated deployments via GitHub. If you are managing deployments using `npx -y firebase-tools@latest deploy`, DO NOT use these commands. + +### `npx -y firebase-tools@latest apphosting:rollouts:create ` + +- **Purpose**: Manually triggers a new rollout (deployment). +- **Options**: + - `--git-branch `: Deploy the latest commit from a specific branch. + - `--git-commit `: Deploy a specific commit. +- **Use Case**: Useful for redeploying without code changes, or rolling back to a specific commit. + +### `npx -y firebase-tools@latest apphosting:backends:create` + +- **Purpose**: Creates a new App Hosting backend. Use this when setting up automated deployments via GitHub. +- **Options**: + - `--app `: The ID of an existing Firebase web app to associate with the backend. + - `--backend `: The ID of the new backend. + - `--primary-region `: The primary region for the backend. + - `--root-dir `: The root directory for the backend. If omitted, defaults to the root directory of the project. + - `--service-account `: The service account used to run the server. If omitted, defaults to the default service account. + \ No newline at end of file diff --git a/.agents/skills/firebase-app-hosting-basics/references/configuration.md b/.agents/skills/firebase-app-hosting-basics/references/configuration.md new file mode 100644 index 0000000..da10766 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/configuration.md @@ -0,0 +1,51 @@ +# App Hosting Configuration (`apphosting.yaml`) + +The `apphosting.yaml` file is the source of truth for your backend's configuration. It must be located in the root of your app's directory (or the specific root directory if using a monorepo). + +## File Structure + +```yaml +# apphosting.yaml + +# Cloud Run service configuration +runConfig: + cpu: 1 + memoryMiB: 512 + minInstances: 0 + maxInstances: 100 + concurrency: 80 + +# Environment variables +env: + - variable: STORAGE_BUCKET + value: mybucket.app + availability: + - BUILD + - RUNTIME + - variable: API_KEY + secret: myApiKeySecret +``` + +## `runConfig` +Controls the resources allocated to the Cloud Run service that serves your app. +- `cpu`: Number of vCPUs. Note: If `< 1`, concurrency MUST be set to `1`. +- `memoryMiB`: RAM in MiB (128 to 32768). +- `minInstances`: Minimum containers to keep warm (default 0). Set to >= 1 to avoid cold starts. +- `maxInstances`: Maximum scaling limit (default 100). +- `concurrency`: Max concurrent requests per instance (default 80). + +### Resource Constraints +- **CPU vs Memory**: Higher memory often requires higher CPU. + - > 4GiB RAM -> Needs >= 2 vCPU + - > 8GiB RAM -> Needs >= 4 vCPU + +## `env` (Environment Variables) +Defines environment variables available during build and/or runtime. + +- `variable`: The name of the env var (e.g., `NEXT_PUBLIC_API_URL`). +- `value`: A literal string value. +- `secret`: The name of a secret in Cloud Secret Manager. use `npx -y firebase-tools@latest apphosting:secrets:set` to create these. +- `availability`: Where the variable is needed. + - `BUILD`: Available during the `npm run build` process. + - `RUNTIME`: Available when the app is serving requests. + - Defaults to both if not specified. diff --git a/.agents/skills/firebase-app-hosting-basics/references/emulation.md b/.agents/skills/firebase-app-hosting-basics/references/emulation.md new file mode 100644 index 0000000..299dcde --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/emulation.md @@ -0,0 +1,47 @@ +# App Hosting Emulation + +You can test your App Hosting setup locally using the Firebase Local Emulator Suite. This allows you to verify your app's behavior with environment variables and secrets before deploying. + +## Configuration: `apphosting.emulator.yaml` +This optional file overrides `apphosting.yaml` settings specifically for the local emulator. Use it to provide local secret values or override resource configs. If it contains sensitive values such as API keys, do not commit it to source control. + +```yaml +# apphosting.emulator.yaml (gitignored usually) +runConfig: + cpu: 1 + memoryMiB: 512 + +env: + - variable: API_KEY + value: "local-dev-api-key" # Override secret with local value +``` + +## Running the Emulator +To start the App Hosting emulator: + +```bash +npx -y firebase-tools@latest emulators:start --only apphosting +``` + +Or, if you are also using other emulators (Auth, Firestore, etc.): + +```bash +npx -y firebase-tools@latest emulators:start +``` + +## Capabilities +- **Builds your app**: Runs the build command defined in your `package.json` to generate the serving artifact. +- **Serves locally**: Runs the app on `localhost:5004` (default). +Configurable by setting `host` and `port` in the `emulators` block of `firebase.json`, like so: + +```json +{ + "emulators": { + "apphosting": { + "host": "localhost", + "port": 5004 + } + } +} +``` +- **Env Var Injection**: Injects variables defined in `apphosting.yaml` and `apphosting.emulator.yaml` into the process. diff --git a/.agents/skills/firebase-auth-basics/SKILL.md b/.agents/skills/firebase-auth-basics/SKILL.md new file mode 100644 index 0000000..bac12ad --- /dev/null +++ b/.agents/skills/firebase-auth-basics/SKILL.md @@ -0,0 +1,86 @@ +--- +name: firebase-auth-basics +description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +## Prerequisites + +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). + +## Core Concepts + +Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. + +### Users + +A user is an entity that can sign in to your app. Each user is identified by a unique ID (`uid`) which is guaranteed to be unique across all providers. +User properties include: +- `uid`: Unique identifier. +- `email`: User's email address (if available). +- `displayName`: User's display name (if available). +- `photoURL`: URL to user's photo (if available). +- `emailVerified`: Boolean indicating if the email is verified. + +### Identity Providers + +Firebase Auth supports multiple ways to sign in: +- **Email/Password**: Basic email and password authentication. +- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub, Microsoft, Apple, etc. +- **Phone Number**: SMS-based authentication. +- **Anonymous**: Temporary guest accounts that can be linked to permanent accounts later. +- **Custom Auth**: Integrate with your existing auth system. + +Google Sign In is recommended as a good and secure default provider. + +### Tokens + +When a user signs in, they receive an ID Token (JWT). This token is used to identify the user when making requests to Firebase services (Realtime Database, Cloud Storage, Firestore) or your own backend. +- **ID Token**: Short-lived (1 hour), verifies identity. +- **Refresh Token**: Long-lived, used to get new ID tokens. + +## Workflow + +### 1. Provisioning + +#### Option 1. Enabling Authentication via CLI + +Only Google Sign In, anonymous auth, and email/password auth can be enabled via CLI. For other providers, use the Firebase Console. + +Configure Firebase Authentication in `firebase.json` by adding an 'auth' block: + +``` +{ + "auth": { + "providers": { + "anonymous": true, + "emailPassword": true, + "googleSignIn": { + "oAuthBrandDisplayName": "Your Brand Name", + "supportEmail": "support@example.com", + "authorizedRedirectUris": ["https://example.com"] + } + } + } +} +``` + +#### Option 2. Enabling Authentication in Console + +Enable other providers in the Firebase Console. + +1. Go to the https://console.firebase.google.com/project/_/authentication/providers +2. Select your project. +3. Enable the desired Sign-in providers (e.g., Email/Password, Google). + +### 2. Client Setup & Usage + +**Web** +See [references/client_sdk_web.md](references/client_sdk_web.md). + +### 3. Security Rules + +Secure your data using `request.auth` in Firestore/Storage rules. + +See [references/security_rules.md](references/security_rules.md). diff --git a/.agents/skills/firebase-auth-basics/references/client_sdk_web.md b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md new file mode 100644 index 0000000..493a66a --- /dev/null +++ b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md @@ -0,0 +1,287 @@ +# Firebase Authentication Web SDK + +## Initialization + +First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize the Auth service: + +```javascript +import { getAuth } from "firebase/auth"; +import { app } from "./firebase"; // Your initialized Firebase App + +const auth = getAuth(app); +export { auth }; +``` + +## Connect to Emulator + +If you are running the Authentication emulator (usually on port 9099), connect to it immediately after initialization. + +```javascript +import { getAuth, connectAuthEmulator } from "firebase/auth"; + +const auth = getAuth(); +// Connect to emulator if running locally +if (location.hostname === "localhost") { + connectAuthEmulator(auth, "http://localhost:9099"); +} +``` + +## Sign Up with Email/Password + +```javascript +import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; + +const auth = getAuth(); +createUserWithEmailAndPassword(auth, email, password) + .then((userCredential) => { + const user = userCredential.user; + // ... + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + // .. + }); +``` + +## Sign In with Google (Popup) + +```javascript +import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GoogleAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // This gives you a Google Access Token. You can use it to access the Google API. + const credential = GoogleAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + // The signed-in user info. + const user = result.user; + // ... + }) + .catch((error) => { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // ... + }); +``` + +## Sign In with Facebook (Popup) + +```javascript +import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new FacebookAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // The signed-in user info. + const user = result.user; + // This gives you a Facebook Access Token. You can use it to access the Facebook API. + const credential = FacebookAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Apple (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('apple.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Apple credential + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Twitter (Popup) + +```javascript +import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new TwitterAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Twitter credential + const credential = TwitterAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + const secret = credential.secret; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with GitHub (Popup) + +```javascript +import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GithubAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = GithubAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Microsoft (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('microsoft.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Yahoo (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('yahoo.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In Anonymously + +```javascript +import { getAuth, signInAnonymously } from "firebase/auth"; + +const auth = getAuth(); +signInAnonymously(auth) + .then(() => { + // Signed in.. + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + }); +``` + +## Email Link Authentication + +**1. Send Auth Link** + +```javascript +import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; + +const auth = getAuth(); +const actionCodeSettings = { + // URL you want to redirect back to. The domain must be in the authorized domains list in Firebase Console. + url: 'https://www.example.com/finishSignUp?cartId=1234', + handleCodeInApp: true, +}; + +sendSignInLinkToEmail(auth, email, actionCodeSettings) + .then(() => { + // Save the email locally so you don't need to ask the user for it again + window.localStorage.setItem('emailForSignIn', email); + }) + .catch((error) => { + // Error + }); +``` + +**2. Complete Sign In (on landing page)** + +```javascript +import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth"; + +const auth = getAuth(); + +if (isSignInWithEmailLink(auth, window.location.href)) { + let email = window.localStorage.getItem('emailForSignIn'); + if (!email) { + email = window.prompt('Please provide your email for confirmation'); + } + + signInWithEmailLink(auth, email, window.location.href) + .then((result) => { + window.localStorage.removeItem('emailForSignIn'); + // You can check result.user + }) + .catch((error) => { + // Error + }); +} +``` + +## Observe Auth State + +Recommended way to get the current user. This listener triggers whenever the user signs in or out. + +```javascript +import { getAuth, onAuthStateChanged } from "firebase/auth"; + +const auth = getAuth(); +onAuthStateChanged(auth, (user) => { + if (user) { + // User is signed in, see docs for a list of available properties + // https://firebase.google.com/docs/reference/js/firebase.User + const uid = user.uid; + // ... + } else { + // User is signed out + // ... + } +}); +``` + +## Sign Out + +```javascript +import { getAuth, signOut } from "firebase/auth"; + +const auth = getAuth(); +signOut(auth).then(() => { + // Sign-out successful. +}).catch((error) => { + // An error happened. +}); +``` diff --git a/.agents/skills/firebase-auth-basics/references/security_rules.md b/.agents/skills/firebase-auth-basics/references/security_rules.md new file mode 100644 index 0000000..5de862a --- /dev/null +++ b/.agents/skills/firebase-auth-basics/references/security_rules.md @@ -0,0 +1,38 @@ +# Authentication in Security Rules + +Firebase Security Rules work with Firebase Authentication to provide rule-based access control. For better advice on writing safe security rules, +enable the `firebase-firestore-basics` or `firebase-storage-basics` skills. + +The `request.auth` variable contains authentication information for the user requesting data. + +## Basic Checks + +### Check if user is signed in +``` +allow read, write: if request.auth != null; +``` + +### Check if user owns the data +Access data only if the document ID matches the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == userId; +``` +(Where `userId` is a path variable, e.g., `match /users/{userId}`) + +### Check if user owns the document (field-based) +Access data only if the document has a `owner_uid` field matching the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == resource.data.owner_uid; +``` + +## Token Properties +`request.auth.token` contains standard JWT claims and custom claims. + +- `request.auth.token.email`: The user's email address. +- `request.auth.token.email_verified`: If the email is verified. +- `request.auth.token.name`: The user's display name. + +### Example: Email Verification Check +``` +allow create: if request.auth.token.email_verified == true; +``` diff --git a/.agents/skills/firebase-basics/SKILL.md b/.agents/skills/firebase-basics/SKILL.md new file mode 100644 index 0000000..25909bb --- /dev/null +++ b/.agents/skills/firebase-basics/SKILL.md @@ -0,0 +1,52 @@ +--- +name: firebase-basics +description: The definitive, foundational skill for ANY Firebase task. Make sure to ALWAYS use this skill whenever the user mentions or interacts with Firebase, even if they do not explicitly ask for it. This skill covers everything from the bare minimum INITIAL setup (Node.js setup, Firebase CLI installation, first-time login) to ongoing operations (core principles, workflows, building, service setup, executing Firebase CLI commands, troubleshooting, refreshing, or updating an existing environment). +--- +# Prerequisites + +Please complete these setup steps before proceeding, and remember your progress to avoid repeating them in future interactions. + +1. **Local Environment Setup:** Verify the environment is properly set up so we can use Firebase tools: + - Run `npx -y firebase-tools@latest --version` to check if the Firebase CLI is installed. + - Verify if the Firebase MCP server is installed using your existing tools. + - If either of these checks fails, please review [references/local-env-setup.md](references/local-env-setup.md) to get the environment ready. + +2. **Authentication:** + Ensure you are logged in to Firebase so that commands have the correct permissions. Run `npx -y firebase-tools@latest login`. For environments without a browser (e.g., remote shells), use `npx -y firebase-tools@latest login --no-localhost`. + - The command should output the current user. + - If you are not logged in, follow the interactive instructions from this command to authenticate. + +3. **Active Project:** + Most Firebase tasks require an active project context. Check the current project by running `npx -y firebase-tools@latest use`. + - If the command outputs `Active Project: `, you can proceed with your task. + - If not, ask the user if they have an existing Firebase Project ID. + - If yes: Set it as the active project and add a default alias by running: + ```bash + npx -y firebase-tools@latest use --add + ``` + - If no: Follow the project creation instructions in [references/firebase-project-create.md](references/firebase-project-create.md). + +# Firebase Usage Principles + +Please adhere to these principles when working with Firebase, as they ensure reliability and up-to-date project tools: + +1. **Use npx for CLI commands:** To ensure you always use the latest version of the Firebase CLI, always prepend commands with `npx -y firebase-tools@latest` instead of just `firebase`. (e.g., use `npx -y firebase-tools@latest --version` instead of `firebase --version`). +2. **Prioritize official knowledge:** For any Firebase-related knowledge, consult the `developerknowledge_search_documents` MCP tool before falling back to Google Search or your internal knowledge base. Including "Firebase" in your search query significantly improves relevance. +3. **Follow Agent Skills for implementation guidance:** Skills provide opinionated workflows (CUJs), security rules, and best practices. Always consult them to understand *how* to implement Firebase features correctly instead of relying on general knowledge. +4. **Use Firebase MCP Server tools instead of direct API calls:** Whenever you need to interact with remote Firebase APIs (such as fetching Crashlytics logs or executing Data Connect queries), use the tools provided by the Firebase MCP Server instead of attempting manual API calls. +5. **Keep Plugin / Agent Skills updated:** Since Firebase best practices evolve quickly, remind the user to regularly check for and install updates to their Firebase plugin or Agent Skills, ensuring you both operate with the latest workflows. Similarly, if you encounter issues with outdated tools or commands, follow the steps below based on your agent environment: + - **Antigravity**: Follow [references/refresh-antigravity.md](references/refresh-antigravity.md) + - **Gemini CLI**: Follow [references/refresh-gemini-cli.md](references/refresh-gemini-cli.md) + - **Claude Code**: Follow [references/refresh-claude.md](references/refresh-claude.md) + - **Cursor**: Follow [references/refresh-cursor.md](references/refresh-cursor.md) + - **Others**: Follow [references/refresh-other.md](references/refresh-other-agents.md) + +# References + +- **Initialize Firebase:** See [references/firebase-service-init.md](references/firebase-service-init.md) when you need to initialize new Firebase services using the CLI. +- **Exploring Commands:** See [references/firebase-cli-guide.md](references/firebase-cli-guide.md) to discover and understand CLI functionality. +- **SDK Setup:** For detailed guides on adding Firebase to a web app, see [references/web_setup.md](references/web_setup.md). + +# Common Issues + +- **Login Issues:** If the browser fails to open during the login step, use `npx -y firebase-tools@latest login --no-localhost` instead. diff --git a/.agents/skills/firebase-basics/references/firebase-cli-guide.md b/.agents/skills/firebase-basics/references/firebase-cli-guide.md new file mode 100644 index 0000000..36a4480 --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-cli-guide.md @@ -0,0 +1,16 @@ +# Exploring Commands + +The Firebase CLI documents itself. Use help commands to discover functionality. + +- **Global Help**: List all available commands and categories. + ```bash + npx -y firebase-tools@latest --help + ``` + +- **Command Help**: Get detailed usage for a specific command. + ```bash + npx -y firebase-tools@latest [command] --help + # Example: + npx -y firebase-tools@latest deploy --help + npx -y firebase-tools@latest firestore:indexes --help + ``` diff --git a/.agents/skills/firebase-basics/references/firebase-project-create.md b/.agents/skills/firebase-basics/references/firebase-project-create.md new file mode 100644 index 0000000..02b0566 --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-project-create.md @@ -0,0 +1,11 @@ +# Creating a Project + +To create a new Firebase project from the CLI: + +```bash +npx -y firebase-tools@latest projects:create +``` + +You will be prompted to: +1. Enter a **Project ID** (must be 6-30 chars, lowercase, digits, and hyphens; must be unique globally). +2. Enter a **display name**. diff --git a/.agents/skills/firebase-basics/references/firebase-service-init.md b/.agents/skills/firebase-basics/references/firebase-service-init.md new file mode 100644 index 0000000..13800aa --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-service-init.md @@ -0,0 +1,18 @@ +# Initialization + +Before initializing, check if you are already in a Firebase project directory by looking for `firebase.json`. + +1. **Project Directory:** + Navigate to the root directory of the codebase. + *(Only if starting a completely new project from scratch without an existing codebase, create a directory first: `mkdir my-project && cd my-project`)* + +2. **Initialize Services:** + Run the initialization command: + ```bash + npx -y firebase-tools@latest init + ``` + +The CLI will guide you through: +- Selecting features (Firestore, Functions, Hosting, etc.). +- Associating with an existing project or creating a new one. +- Configuring files (e.g. `firebase.json`, `.firebaserc`). diff --git a/.agents/skills/firebase-basics/references/local-env-setup.md b/.agents/skills/firebase-basics/references/local-env-setup.md new file mode 100644 index 0000000..99e6019 --- /dev/null +++ b/.agents/skills/firebase-basics/references/local-env-setup.md @@ -0,0 +1,65 @@ +# Firebase Local Environment Setup + +This skill documents the bare minimum setup required for a full Firebase experience for the agent. Before starting to use any Firebase features, you MUST verify that each of the following steps has been completed. + +## 1. Verify Node.js +- **Action**: Run `node --version`. +- **Handling**: Ensure Node.js is installed and the version is `>= 20`. If Node.js is missing or `< v20`, install it based on the operating system: + + **Recommended: Use a Node Version Manager** + This avoids permission issues when installing global packages. + + **For macOS or Linux:** + 1. Guide the user to the [official nvm repository](https://github.com/nvm-sh/nvm#installing-and-updating). + 2. Request the user to manually install `nvm` and reply when finished. **Stop and wait** for the user's confirmation. + 3. Make `nvm` available in the current terminal session by sourcing the appropriate profile: + ```bash + # For Bash + source ~/.bash_profile + source ~/.bashrc + + # For Zsh + source ~/.zprofile + source ~/.zshrc + ``` + 4. Install Node.js: + ```bash + nvm install 24 + nvm use 24 + ``` + + **For Windows:** + 1. Guide the user to download and install [nvm-windows](https://github.com/coreybutler/nvm-windows/releases). + 2. Request the user to manually install `nvm-windows` and Node.js, and reply when finished. **Stop and wait** for the user's confirmation. + 3. After the user confirms, verify Node.js is available: + ```bash + node --version + ``` + + **Alternative: Official Installer** + 1. Guide the user to download and install the LTS version from [nodejs.org](https://nodejs.org/en/download). + 2. Request the user to manually install Node.js and reply when finished. **Stop and wait** for the user's confirmation. + +## 2. Verify Firebase CLI +The Firebase CLI is the primary tool for interacting with Firebase services. +- **Action**: Run `npx -y firebase-tools@latest --version`. +- **Handling**: Ensure this command runs successfully and outputs a version number. + +## 3. Verify Firebase Authentication +You must be authenticated to manage Firebase projects. +- **Action**: Run `npx -y firebase-tools@latest login`. +- **Handling**: If the environment is remote or restricted (no browser access), run `npx -y firebase-tools@latest login --no-localhost` instead. + +## 4. Install Agent Skills and MCP Server +To fully manage Firebase, the agent needs specific skills and the Firebase MCP server installed. Identify the agent environment you are currently running in and follow the corresponding setup document strictly. + +**Read the setup document for your current agent:** +- **Gemini CLI**: Review [setup-gemini_cli.md](setup-gemini_cli.md) +- **Antigravity**: Review [setup-antigravity.md](setup-antigravity.md) +- **Claude Code**: Review [setup-claude_code.md](setup-claude_code.md) +- **Cursor**: Review [setup-cursor.md](setup-cursor.md) +- **GitHub Copilot**: Review [setup-github_copilot.md](setup-github_copilot.md) +- **Other Agents** (Windsurf, Cline, etc.): Review [setup-other_agents.md](setup-other_agents.md) + +--- +**CRITICAL AGENT RULE:** Do NOT proceed with any other Firebase tasks until EVERY step above has been successfully verified and completed. diff --git a/.agents/skills/firebase-basics/references/refresh-antigravity.md b/.agents/skills/firebase-basics/references/refresh-antigravity.md new file mode 100644 index 0000000..6f5ee32 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-antigravity.md @@ -0,0 +1,46 @@ +# Refresh Antigravity Local Environment + +Follow these steps to refresh Antigravity's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Antigravity relies on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent antigravity + + # Check global-level skills + npx -y skills list --agent antigravity --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to Antigravity.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent antigravity --yes + + # Update global-level skills + npx -y skills update --agent antigravity --global --yes + ``` diff --git a/.agents/skills/firebase-basics/references/refresh-claude.md b/.agents/skills/firebase-basics/references/refresh-claude.md new file mode 100644 index 0000000..772314e --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-claude.md @@ -0,0 +1,10 @@ +# Refresh Claude Code Local Environment + +Follow these steps to refresh Claude Code's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use Claude Code's native plugin manager instead of `npx`. + +1. **Update the Plugin:** Run the specific CLI command to update the Firebase plugin: + ```bash + claude plugin update firebase@firebase + ``` \ No newline at end of file diff --git a/.agents/skills/firebase-basics/references/refresh-gemini-cli.md b/.agents/skills/firebase-basics/references/refresh-gemini-cli.md new file mode 100644 index 0000000..6cc1467 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-gemini-cli.md @@ -0,0 +1,11 @@ +# Refresh Gemini CLI Local Environment + +Follow these steps to refresh Gemini CLI's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use the native Gemini CLI extension manager instead of `npx`. + +1. **Update the Extension:** Run the specific CLI command to update: + ```bash + gemini extensions update firebase + ``` + *Note: If the extension is named differently, replace `firebase` with the correct name from `gemini extensions list`.* diff --git a/.agents/skills/firebase-basics/references/refresh-other-agents.md b/.agents/skills/firebase-basics/references/refresh-other-agents.md new file mode 100644 index 0000000..f624c96 --- /dev/null +++ b/.agents/skills/firebase-basics/references/refresh-other-agents.md @@ -0,0 +1,48 @@ +# Refresh Other Local Environment + +Follow these steps to refresh the local environment of other agents, ensuring that their agent skills and plugins are fully up-to-date. + +Other agents rely on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +Replace `` with the actual agent name, which can be found in the [skills repository README](https://github.com/vercel-labs/skills/blob/main/README.md). + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked for the agent at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent + + # Check global-level skills + npx -y skills list --agent --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to the agent.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent --yes + + # Update global-level skills + npx -y skills update --agent --global --yes + ``` diff --git a/.agents/skills/firebase-basics/references/setup-antigravity.md b/.agents/skills/firebase-basics/references/setup-antigravity.md new file mode 100644 index 0000000..7817673 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-antigravity.md @@ -0,0 +1,63 @@ +# Antigravity Setup + +To get the most out of Firebase in Antigravity, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `ls -d .agent/skills/firebase-basics` or `ls -d .agents/skills/firebase-basics`. If the directory exists, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent antigravity + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent antigravity --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Antigravity to interact directly with Firebase projects. + +1. **Locate `mcp_config.json`**: Find the configuration file for your operating system: + - macOS / Linux: `~/.gemini/antigravity/mcp_config.json` + - Windows: `%USERPROFILE%\\.gemini\\antigravity\\mcp_config.json` + + *Note: If the `.gemini/antigravity/` directory or `mcp_config.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp_config.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp_config.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Antigravity**: Instruct the user to restart the Antigravity application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Antigravity UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-claude_code.md b/.agents/skills/firebase-basics/references/setup-claude_code.md new file mode 100644 index 0000000..fe8eba6 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-claude_code.md @@ -0,0 +1,30 @@ +# Claude Code Setup + +To get the most out of Firebase in Claude Code, follow these steps to install the agent skills and the MCP server. + +## Recommended Method: Using Plugins + +The recommended method is using the plugin marketplace to install both the agent skills and the MCP functionality. + +### 1. Install and Verify Plugins + +Check if the plugins are already installed before proceeding: + +1. **Check Existing Skills**: Run `npx skills list --agent claude-code` to check for local skills. Run `npx skills list --global --agent claude-code` to check for global skills. Note whether the output includes `firebase-basics`. +2. **Check Existing MCP Configuration**: Run `claude mcp list -s user` and `claude mcp list -s project`. Note whether the output of either command includes `firebase`. +3. **Determine Installation Path**: + - If **both** skills and MCP configuration are found, the plugin is fully installed. **Stop here and skip all remaining setup steps in this document.** + - If **neither** are found, proceed to step 4. + - If **only one** is found (e.g., skills are installed but MCP is missing, or vice versa), **stop and prompt the user**. Explain the mixed state and ask if they want to proceed with installing the Firebase plugin before continuing to step 4. +4. **Add Marketplace**: Run the following command to add the marketplace (this uses the default User scope): + ```bash + claude plugin marketplace add firebase/agent-skills + ``` +5. **Install Plugins**: Run the following command to install the plugin: + ```bash + claude plugin install firebase@firebase + ``` +6. **Verify Installation**: Re-run the checks in steps 1 and 2 to confirm the skills and the MCP server are now available. + +### 2. Restart and Verify Connection +1. **Restart Claude Code**: Instruct the user to restart Claude Code. **Stop and wait** for their confirmation before proceeding. diff --git a/.agents/skills/firebase-basics/references/setup-cursor.md b/.agents/skills/firebase-basics/references/setup-cursor.md new file mode 100644 index 0000000..c74360e --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-cursor.md @@ -0,0 +1,63 @@ +# Cursor Setup + +To get the most out of Firebase in Cursor, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent cursor`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent cursor + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent cursor --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Cursor to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your operating system: + - Global: `~/.cursor/mcp.json` + - Project: `.cursor/mcp.json` + + *Note: If the directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Cursor**: Instruct the user to restart the Cursor application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Cursor UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-gemini_cli.md b/.agents/skills/firebase-basics/references/setup-gemini_cli.md new file mode 100644 index 0000000..ebadeaa --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-gemini_cli.md @@ -0,0 +1,39 @@ +# Gemini CLI Setup + +To get the most out of Firebase in the Gemini CLI, follow these steps to install the agent extension and the MCP server. + +## Recommended: Installing Extensions + +The best way to get both the agent skills and the MCP server is via the Gemini extension. + +### 1. Install and Verify Firebase Extension +Check if the extension is already installed before proceeding: + +1. **Check Existing Extensions**: Run `gemini extensions list`. If the output includes `firebase`, the extension is already installed. +2. **Install Extension**: If not found, run the following command to install the Firebase agent skills and MCP server: + ```bash + gemini extensions install https://github.com/firebase/agent-skills + ``` +3. **Verify Installation**: Run the following checks to confirm installation: + - `gemini mcp list` -> Output should include `firebase-tools`. + - `gemini skills list` -> Output should include `firebase-basic`. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI if any new installation occurred. **Stop and wait** for their confirmation before proceeding. + +--- + +## Alternative: Manual MCP Configuration (Project Scope) + +If the user only wants to use the MCP server for the current project: + +### 1. Configure and Verify Firebase MCP Server +1. **Check Existing Configuration**: Run `gemini mcp list`. If the output includes `firebase-tools`, the MCP server is already configured. +2. **Add the MCP Server**: If not found, run the following command to configure the Firebase MCP Server: + ```bash + gemini mcp add -e IS_GEMINI_CLI_EXTENSION=true firebase npx -y firebase-tools@latest mcp + ``` +3. **Verify Configuration**: Re-run `gemini mcp list` to confirm `firebase-tools` is connected. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI. **Stop and wait** for their confirmation before proceeding. diff --git a/.agents/skills/firebase-basics/references/setup-github_copilot.md b/.agents/skills/firebase-basics/references/setup-github_copilot.md new file mode 100644 index 0000000..1704cb5 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-github_copilot.md @@ -0,0 +1,70 @@ +# GitHub Copilot Setup + +To get the most out of Firebase with GitHub Copilot in VS Code, follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent github-copilot`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent github-copilot + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent github-copilot --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows GitHub Copilot to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your environment: + - Workspace: `.vscode/mcp.json` + - Global: User Settings `mcp.json` file. + + *Note: If the `.vscode/` directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcp": { "servers": {} } }` before proceeding.* +2. **Check Existing Configuration**: Open the `mcp.json` file and check the `mcp.servers` object for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "type": "stdio", + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcp.servers` object: + ```json + "firebase": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file under the `mcp.servers` object. You MUST preserve any other existing servers inside `mcp.servers`.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart VS Code**: Instruct the user to restart VS Code. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the VS Code Copilot UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/setup-other_agents.md b/.agents/skills/firebase-basics/references/setup-other_agents.md new file mode 100644 index 0000000..d45a608 --- /dev/null +++ b/.agents/skills/firebase-basics/references/setup-other_agents.md @@ -0,0 +1,65 @@ +# Other Agents Setup + +If you use another agent (like Windsurf, Cline, or Claude Desktop), follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent `. If the output includes `firebase-basics`, the skills are already installed locally. Replace `` with the actual agent name, which can be found [here](https://github.com/vercel-labs/skills/blob/main/README.md). +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows the agent to interact directly with Firebase projects. + +1. **Locate MCP Configuration**: Find the configuration file for your agent (e.g., `~/.codeium/windsurf/mcp_config.json`, `cline_mcp_settings.json`, or `claude_desktop_config.json`). + + *Note: If the document or its containing directory does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open the configuration file and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx", + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase", + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx", + "args": [ + "-y", + "firebase-tools@latest", + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Agent**: Instruct the user to restart the agent application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the agent's UI to confirm that the Firebase MCP server is connected. diff --git a/.agents/skills/firebase-basics/references/web_setup.md b/.agents/skills/firebase-basics/references/web_setup.md new file mode 100644 index 0000000..b696118 --- /dev/null +++ b/.agents/skills/firebase-basics/references/web_setup.md @@ -0,0 +1,69 @@ +# Firebase Web Setup Guide + +## 1. Create a Firebase Project and App +If you haven't already created a project: + +```bash +npx -y firebase-tools@latest projects:create +``` + +Register your web app: +```bash +npx -y firebase-tools@latest apps:create web my-web-app +``` +(Note the **App ID** returned by this command). + +## 2. Installation +Install the Firebase SDK via npm: + +```bash +npm install firebase +``` + +## 3. Initialization +Create a `firebase.js` (or `firebase.ts`) file. You can fetch your config object using the CLI: + +```bash +npx -y firebase-tools@latest apps:sdkconfig +``` + +Copy the output config object into your initialization file: + +```javascript +import { initializeApp } from "firebase/app"; +import { getAuth } from "firebase/auth"; + +// Your web app's Firebase configuration +const firebaseConfig = { + apiKey: "API_KEY", + authDomain: "PROJECT_ID.firebaseapp.com", + projectId: "PROJECT_ID", + storageBucket: "PROJECT_ID.firebasestorage.app", + messagingSenderId: "SENDER_ID", + appId: "APP_ID", + measurementId: "G-MEASUREMENT_ID" +}; + +// Initialize Firebase +const app = initializeApp(firebaseConfig); +const auth = getAuth(app); + +export { app }; +``` + +## 4. Using Services +Import specific services as needed (Modular API): + +```javascript +import { getFirestore, collection, getDocs } from "firebase/firestore"; +import { app } from "./firebase"; // Import the initialized app + +const db = getFirestore(app); + +async function getUsers() { + const querySnapshot = await getDocs(collection(db, "users")); + querySnapshot.forEach((doc) => { + console.log(`${doc.id} => ${doc.data()}`); + }); +} +``` diff --git a/.agents/skills/firebase-data-connect/SKILL.md b/.agents/skills/firebase-data-connect/SKILL.md new file mode 100644 index 0000000..e87a3c1 --- /dev/null +++ b/.agents/skills/firebase-data-connect/SKILL.md @@ -0,0 +1,95 @@ +--- +name: firebase-data-connect +description: Build and deploy Firebase Data Connect backends with PostgreSQL. Use for schema design, GraphQL queries/mutations, authorization, and SDK generation for web, Android, iOS, and Flutter apps. +--- + +# Firebase Data Connect + +Firebase Data Connect is a relational database service using Cloud SQL for PostgreSQL with GraphQL schema, auto-generated queries/mutations, and type-safe SDKs. + +## Project Structure + +``` +dataconnect/ +├── dataconnect.yaml # Service configuration +├── schema/ +│ └── schema.gql # Data model (types with @table) +└── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Queries + └── mutations.gql # Mutations +``` + +## Development Workflow + +Follow this strict workflow to build your application. You **must** read the linked reference files for each step to understand the syntax and available features. + +### 1. Define Data Model (`schema/schema.gql`) +Define your GraphQL types, tables, and relationships. +> **Read [reference/schema.md](reference/schema.md)** for: +> * `@table`, `@col`, `@default` +> * Relationships (`@ref`, one-to-many, many-to-many) +> * Data types (UUID, Vector, JSON, etc.) + +### 2. Define Operations (`connector/queries.gql`, `connector/mutations.gql`) +Write the queries and mutations your client will use. Data Connect generates the underlying SQL. +> **Read [reference/operations.md](reference/operations.md)** for: +> * **Queries**: Filtering (`where`), Ordering (`orderBy`), Pagination (`limit`/`offset`). +> * **Mutations**: Create (`_insert`), Update (`_update`), Delete (`_delete`). +> * **Upserts**: Use `_upsert` to "insert or update" records (CRITICAL for user profiles). +> * **Transactions**: use `@transaction` for multi-step atomic operations. + +### 3. Secure Your App (`connector/` files) +Add authorization logic closely with your operations. +> **Read [reference/security.md](reference/security.md)** for: +> * `@auth(level: ...)` for PUBLIC, USER, or NO_ACCESS. +> * `@check` and `@redact` for row-level security and validation. + +### 4. Generate & Use SDKs +Generate type-safe code for your client platform. +> **Read [reference/sdks.md](reference/sdks.md)** for: +> * Android (Kotlin), iOS (Swift), Web (TypeScript), Flutter (Dart). +> * How to initialize and call your queries/mutations. +> * **Nested Data**: See how to access related fields (e.g., `movie.reviews`). + +--- + +## Feature Capability Map + +If you need to implement a specific feature, consult the mapped reference file: + +| Feature | Reference File | Key Concepts | +| :--- | :--- | :--- | +| **Data Modeling** | [reference/schema.md](reference/schema.md) | `@table`, `@unique`, `@index`, Relations | +| **Vector Search** | [reference/advanced.md](reference/advanced.md) | `Vector`, `@col(dataType: "vector")` | +| **Full-Text Search** | [reference/advanced.md](reference/advanced.md) | `@searchable` | +| **Upserting Data** | [reference/operations.md](reference/operations.md) | `_upsert` mutations | +| **Complex Filters** | [reference/operations.md](reference/operations.md) | `_or`, `_and`, `_not`, `eq`, `contains` | +| **Transactions** | [reference/operations.md](reference/operations.md) | `@transaction`, `response` binding | +| **Environment Config** | [reference/config.md](reference/config.md) | `dataconnect.yaml`, `connector.yaml` | + +--- + +## Deployment & CLI + +> **Read [reference/config.md](reference/config.md)** for deep dive on configuration. + +Common commands (run from project root): + +```bash +# Initialize Data Connect +npx -y firebase-tools@latest init dataconnect + +# Start local emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDK code +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +## Examples + +For complete, working code examples of schemas and operations, see **[examples.md](examples.md)**. diff --git a/.agents/skills/firebase-data-connect/examples.md b/.agents/skills/firebase-data-connect/examples.md new file mode 100644 index 0000000..87a6e3d --- /dev/null +++ b/.agents/skills/firebase-data-connect/examples.md @@ -0,0 +1,377 @@ +# Examples + +Complete, working examples for common Data Connect use cases. + +--- + +## Movie Review App + +A complete schema for a movie database with reviews, actors, and user authentication. + +### Schema + +```graphql +# schema.gql + +# Users +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movies +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + releaseYear: Int + genre: String @index + rating: Float + description: String + posterUrl: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movie metadata (one-to-one) +type MovieMetadata @table { + movie: Movie! @unique + director: String + runtime: Int + budget: Int64 +} + +# Actors +type Actor @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + birthDate: Date +} + +# Movie-Actor relationship (many-to-many) +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # "lead" or "supporting" + character: String +} + +# Reviews (user-owned) +type Review @table @unique(fields: ["movie", "user"]) { + id: UUID! @default(expr: "uuidV4()") + movie: Movie! + user: User! + rating: Int! + text: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Queries + +```graphql +# queries.gql + +# Public: List movies with filtering +query ListMovies($genre: String, $minRating: Float, $limit: Int) + @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ rating: DESC }], + limit: $limit + ) { + id title genre rating releaseYear posterUrl + } +} + +# Public: Get movie with full details +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre rating releaseYear description + metadata: movieMetadata_on_movie { director runtime } + actors: actors_via_MovieActor { name } + reviews: reviews_on_movie(orderBy: [{ createdAt: DESC }], limit: 10) { + rating text createdAt + user { displayName } + } + } +} + +# User: Get my reviews +query MyReviews @auth(level: USER) { + reviews(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + id rating text createdAt + movie { id title posterUrl } + } +} +``` + +### Mutations + +```graphql +# mutations.gql + +# User: Create/update profile on first login +mutation UpsertUser($email: String!, $displayName: String) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + displayName: $displayName + }) +} + +# User: Add review (one per movie per user) +mutation AddReview($movieId: UUID!, $rating: Int!, $text: String) + @auth(level: USER) { + review_upsert(data: { + movie: { id: $movieId }, + user: { uid_expr: "auth.uid" }, + rating: $rating, + text: $text + }) +} + +# User: Delete my review +mutation DeleteReview($id: UUID!) @auth(level: USER) { + review_delete( + first: { where: { + id: { eq: $id }, + user: { uid: { eq_expr: "auth.uid" }} + }} + ) +} +``` + +--- + +## E-Commerce Store + +Products, orders, and cart management with user authentication. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String + shippingAddress: String +} + +type Product @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @index + description: String + price: Float! + stock: Int! @default(value: 0) + category: String @index + imageUrl: String +} + +type CartItem @table(key: ["user", "product"]) { + user: User! + product: Product! + quantity: Int! +} + +enum OrderStatus { + PENDING + PAID + SHIPPED + DELIVERED + CANCELLED +} + +type Order @table { + id: UUID! @default(expr: "uuidV4()") + user: User! + status: OrderStatus! @default(value: PENDING) + total: Float! + shippingAddress: String! + createdAt: Timestamp! @default(expr: "request.time") +} + +type OrderItem @table { + id: UUID! @default(expr: "uuidV4()") + order: Order! + product: Product! + quantity: Int! + priceAtPurchase: Float! +} +``` + +### Operations + +```graphql +# Public: Browse products +query ListProducts($category: String, $search: String) @auth(level: PUBLIC) { + products(where: { + category: { eq: $category }, + name: { contains: $search }, + stock: { gt: 0 } + }) { + id name price stock imageUrl + } +} + +# User: View cart +query MyCart @auth(level: USER) { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + quantity + product { id name price imageUrl stock } + } +} + +# User: Add to cart +mutation AddToCart($productId: UUID!, $quantity: Int!) @auth(level: USER) { + cartItem_upsert(data: { + user: { uid_expr: "auth.uid" }, + product: { id: $productId }, + quantity: $quantity + }) +} + +# User: Checkout (transactional) +mutation Checkout($shippingAddress: String!) + @auth(level: USER) + @transaction { + # Query cart items + query @redact { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) + @check(expr: "this.size() > 0", message: "Cart is empty") { + quantity + product { id price } + } + } + # Create order (in real app, calculate total from cart) + order_insert(data: { + user: { uid_expr: "auth.uid" }, + shippingAddress: $shippingAddress, + total: 0 # Calculate in app logic + }) +} +``` + +--- + +## Blog with Permissions + +Multi-author blog with role-based permissions. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String! + bio: String +} + +enum UserRole { + VIEWER + AUTHOR + EDITOR + ADMIN +} + +type BlogPermission @table(key: ["user"]) { + user: User! + role: UserRole! @default(value: VIEWER) +} + +enum PostStatus { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! + title: String! @searchable + content: String! @searchable + status: PostStatus! @default(value: DRAFT) + publishedAt: Timestamp + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} + +type Comment @table { + id: UUID! @default(expr: "uuidV4()") + post: Post! + author: User! + content: String! + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Operations with Role Checks + +```graphql +# Public: Read published posts +query PublishedPosts @auth(level: PUBLIC) { + posts( + where: { status: { eq: PUBLISHED }}, + orderBy: [{ publishedAt: DESC }] + ) { + id title content publishedAt + author { name } + } +} + +# Author+: Create post +mutation CreatePost($title: String!, $content: String!) + @auth(level: USER) + @transaction { + # Check user is at least AUTHOR + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) + @check(expr: "this != null", message: "No permission record") { + role @check(expr: "this in ['AUTHOR', 'EDITOR', 'ADMIN']", message: "Must be author+") + } + } + post_insert(data: { + author: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +# Editor+: Publish any post +mutation PublishPost($id: UUID!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this in ['EDITOR', 'ADMIN']", message: "Must be editor+") + } + } + post_update(id: $id, data: { + status: PUBLISHED, + publishedAt_expr: "request.time" + }) +} + +# Admin: Grant role +mutation GrantRole($userUid: String!, $role: UserRole!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this == 'ADMIN'", message: "Must be admin") + } + } + blogPermission_upsert(data: { + user: { uid: $userUid }, + role: $role + }) +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/advanced.md b/.agents/skills/firebase-data-connect/reference/advanced.md new file mode 100644 index 0000000..bdffe7c --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/advanced.md @@ -0,0 +1,303 @@ +# Advanced Features Reference + +## Contents +- [Vector Similarity Search](#vector-similarity-search) +- [Full-Text Search](#full-text-search) +- [Cloud Functions Integration](#cloud-functions-integration) +- [Data Seeding & Bulk Operations](#data-seeding--bulk-operations) + +--- + +## Vector Similarity Search + +Semantic search using Vertex AI embeddings and PostgreSQL's `pgvector`. + +### Schema Setup + +```graphql +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + description: String + # Vector field for embeddings - size must match model output (768 for gecko) + descriptionEmbedding: Vector! @col(size: 768) +} +``` + +### Generate Embeddings in Mutations + +Use `_embed` server value to auto-generate embeddings via Vertex AI: + +```graphql +mutation CreateMovieWithEmbedding($title: String!, $description: String!) + @auth(level: USER) { + movie_insert(data: { + title: $title, + description: $description, + descriptionEmbedding_embed: { + model: "textembedding-gecko@003", + text: $description + } + }) +} +``` + +### Similarity Search Query + +Data Connect generates `_similarity` fields for Vector columns: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare_embed: { model: "textembedding-gecko@003", text: $query }, + method: L2, # L2, COSINE, or INNER_PRODUCT + within: 2.0, # Max distance threshold + limit: 5 + ) { + id + title + description + _metadata { distance } # See how close each result is + } +} +``` + +### Similarity Parameters + +| Parameter | Description | +|-----------|-------------| +| `compare` | Raw Vector to compare against | +| `compare_embed` | Generate embedding from text via Vertex AI | +| `method` | Distance function: `L2`, `COSINE`, `INNER_PRODUCT` | +| `within` | Max distance (results further are excluded) | +| `where` | Additional filters | +| `limit` | Max results to return | + +### Custom Embeddings + +Pass pre-computed vectors directly: + +```graphql +mutation StoreCustomEmbedding($id: UUID!, $embedding: Vector!) @auth(level: USER) { + movie_update(id: $id, data: { descriptionEmbedding: $embedding }) +} + +query SearchWithCustomVector($vector: Vector!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare: $vector, + method: COSINE, + limit: 10 + ) { id title } +} +``` + +--- + +## Full-Text Search + +Fast keyword/phrase search using PostgreSQL's full-text capabilities. + +### Enable with @searchable + +```graphql +type Movie @table { + title: String! @searchable + description: String @searchable(language: "english") + genre: String @searchable +} +``` + +### Search Query + +Data Connect generates `_search` fields: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + queryFormat: QUERY, # QUERY, PLAIN, PHRASE, or ADVANCED + limit: 20 + ) { + id title description + _metadata { relevance } # Relevance score + } +} +``` + +### Query Formats + +| Format | Description | +|--------|-------------| +| `QUERY` | Web-style (default): quotes, AND, OR supported | +| `PLAIN` | Match all words, any order | +| `PHRASE` | Match exact phrase | +| `ADVANCED` | Full tsquery syntax | + +### Tuning Results + +```graphql +query SearchWithThreshold($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query, + relevanceThreshold: 0.05, # Min relevance score + where: { genre: { eq: "Action" }}, + orderBy: [{ releaseYear: DESC }] + ) { id title } +} +``` + +### Supported Languages + +`english` (default), `french`, `german`, `spanish`, `italian`, `portuguese`, `dutch`, `danish`, `finnish`, `norwegian`, `swedish`, `russian`, `arabic`, `hindi`, `simple` + +--- + +## Cloud Functions Integration + +Trigger Cloud Functions when mutations execute. + +### Basic Trigger (Node.js) + +```typescript +import { onMutationExecuted } from "firebase-functions/dataconnect"; +import { logger } from "firebase-functions"; + +export const onUserCreate = onMutationExecuted( + { + service: "myService", + connector: "default", + operation: "CreateUser", + region: "us-central1" // Must match Data Connect location + }, + (event) => { + const variables = event.data.payload.variables; + const returnedData = event.data.payload.data; + + logger.info("User created:", returnedData); + // Send welcome email, sync to analytics, etc. + } +); +``` + +### Basic Trigger (Python) + +```python +from firebase_functions import dataconnect_fn, logger + +@dataconnect_fn.on_mutation_executed( + service="myService", + connector="default", + operation="CreateUser" +) +def on_user_create(event: dataconnect_fn.Event): + variables = event.data.payload.variables + returned_data = event.data.payload.data + logger.info("User created:", returned_data) +``` + +### Event Data + +```typescript +// event.authType: "app_user" | "unauthenticated" | "admin" +// event.authId: Firebase Auth UID (for app_user) +// event.data.payload.variables: mutation input variables +// event.data.payload.data: mutation response data +// event.data.payload.errors: any errors that occurred +``` + +### Filtering with Wildcards + +```typescript +// Trigger on all User* mutations +export const onUserMutation = onMutationExecuted( + { operation: "User*" }, + (event) => { /* ... */ } +); + +// Capture operation name +export const onAnyMutation = onMutationExecuted( + { service: "myService", operation: "{operationName}" }, + (event) => { + console.log("Operation:", event.params.operationName); + } +); +``` + +### Use Cases + +- **Data sync**: Replicate to Firestore, BigQuery, external APIs +- **Notifications**: Send emails, push notifications on events +- **Async workflows**: Image processing, data aggregation +- **Audit logging**: Track all data changes + +> ⚠️ **Avoid infinite loops**: Don't trigger mutations that would fire the same trigger. Use filters to exclude self-triggered events. + +--- + +## Data Seeding & Bulk Operations + +### Local Prototyping with _insertMany + +```graphql +mutation SeedMovies @transaction { + movie_insertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" }, + { id: "uuid-3", title: "Movie 3", genre: "Comedy" } + ]) +} +``` + +### Reset Data with _upsertMany + +```graphql +mutation ResetData { + movie_upsertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } + ]) +} +``` + +### Clear All Data + +```graphql +mutation ClearMovies { + movie_deleteMany(all: true) +} +``` + +### Production: Admin SDK Bulk Operations + +```typescript +import { initializeApp } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +const app = initializeApp(); +const dc = getDataConnect({ location: "us-central1", serviceId: "my-service" }); + +const movies = [ + { id: "uuid-1", title: "Movie 1", genre: "Action" }, + { id: "uuid-2", title: "Movie 2", genre: "Drama" } +]; + +// Bulk insert +await dc.insertMany("movie", movies); + +// Bulk upsert +await dc.upsertMany("movie", movies); + +// Single operations +await dc.insert("movie", movies[0]); +await dc.upsert("movie", movies[0]); +``` + +### Emulator Data Persistence + +```bash +# Export emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with saved data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` diff --git a/.agents/skills/firebase-data-connect/reference/config.md b/.agents/skills/firebase-data-connect/reference/config.md new file mode 100644 index 0000000..c7e5c52 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/config.md @@ -0,0 +1,267 @@ +# Configuration Reference + +## Contents +- [Project Structure](#project-structure) +- [dataconnect.yaml](#dataconnectyaml) +- [connector.yaml](#connectoryaml) +- [Firebase CLI Commands](#firebase-cli-commands) +- [Emulator](#emulator) +- [Deployment](#deployment) + +--- + +## Project Structure + +``` +project-root/ +├── firebase.json # Firebase project config +└── dataconnect/ + ├── dataconnect.yaml # Service configuration + ├── schema/ + │ └── schema.gql # Data model (types, relationships) + └── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Query operations + └── mutations.gql # Mutation operations (optional separate file) +``` + +--- + +## dataconnect.yaml + +Main Data Connect service configuration: + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schemaValidation: "STRICT" # or "COMPATIBLE" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +| Field | Description | +|-------|-------------| +| `specVersion` | Always `"v1"` | +| `serviceId` | Unique identifier for the service | +| `location` | GCP region (us-central1, us-east4, europe-west1, etc.) | +| `schemaValidation` | Deployment mode: `"STRICT"` (must match exactly) or `"COMPATIBLE"` (backward compatible) | +| `schema.source` | Path to schema directory | +| `schema.datasource` | PostgreSQL connection config | +| `connectorDirs` | List of connector directories | + +### Cloud SQL Configuration + +```yaml +schema: + datasource: + postgresql: + database: "my-database" # Database name + cloudSql: + instanceId: "my-instance" # Cloud SQL instance ID +``` + +--- + +## connector.yaml + +Connector configuration and SDK generation: + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" +``` + +### SDK Generation Options + +| SDK | Fields | +|-----|--------| +| `javascriptSdk` | `outputDir`, `package` | +| `kotlinSdk` | `outputDir`, `package` | +| `swiftSdk` | `outputDir` | +| `nodeAdminSdk` | `outputDir`, `package` (for Admin SDK) | + +--- + +## Firebase CLI Commands + +### Initialize Data Connect + +```bash +# Interactive setup +npx -y firebase-tools@latest init dataconnect + +# Set project +npx -y firebase-tools@latest use +``` + +### Local Development + +```bash +# Start emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Start with database seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Watch for schema changes (auto-regenerate) +npx -y firebase-tools@latest dataconnect:sdk:generate --watch +``` + +### Schema Management + +```bash +# Compare local schema to production +npx -y firebase-tools@latest dataconnect:sql:diff + + +# Apply migration +npx -y firebase-tools@latest dataconnect:sql:migrate +``` + +### Deployment + +```bash +# Deploy Data Connect service +npx -y firebase-tools@latest deploy --only dataconnect + +# Deploy specific connector +npx -y firebase-tools@latest deploy --only dataconnect:connector-id + +# Deploy with schema migration +npx -y firebase-tools@latest deploy --only dataconnect --force +``` + +--- + +## Emulator + +### Start Emulator + +```bash +npx -y firebase-tools@latest emulators:start --only dataconnect +``` + +Default ports: +- Data Connect: `9399` +- PostgreSQL: `9939` (local PostgreSQL instance) + +### Emulator Configuration (firebase.json) + +```json +{ + "emulators": { + "dataconnect": { + "port": 9399 + } + } +} +``` + +### Connect from SDK + +```typescript +// Web +import { connectDataConnectEmulator } from 'firebase/data-connect'; +connectDataConnectEmulator(dc, 'localhost', 9399); + +// Android +connector.dataConnect.useEmulator("10.0.2.2", 9399) + +// iOS +connector.useEmulator(host: "localhost", port: 9399) + + +``` + +### Seed Data + +Create seed data files and import: + +```bash +# Export current emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` + +--- + +## Deployment + +### Deploy Workflow + +1. **Test locally** with emulator +2. **Generate SQL diff**: `npx -y firebase-tools@latest dataconnect:sql:diff` +3. **Review migration**: Check breaking changes +4. **Deploy**: `npx -y firebase-tools@latest deploy --only dataconnect` + +### Schema Migrations + +Data Connect auto-generates PostgreSQL migrations: + +```bash +# Preview migration +npx -y firebase-tools@latest dataconnect:sql:diff + +# Apply migration (interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate + +# Force migration (non-interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate --force +``` + +### Breaking Changes + +Some schema changes require special handling: +- Removing required fields +- Changing field types +- Removing tables + +Use `--force` flag to acknowledge breaking changes during deploy. + +### CI/CD Integration + +```yaml +# GitHub Actions example +- name: Deploy Data Connect + run: | + npx -y firebase-tools@latest deploy --only dataconnect --token ${{ secrets.FIREBASE_TOKEN }} --force +``` + +--- + +## VS Code Extension + +Install "Firebase Data Connect" extension for: +- Schema intellisense and validation +- GraphQL operation testing +- Emulator integration +- SDK generation on save + +### Extension Settings + +```json +{ + "firebase.dataConnect.autoGenerateSdk": true, + "firebase.dataConnect.emulator.port": 9399 +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/operations.md b/.agents/skills/firebase-data-connect/reference/operations.md new file mode 100644 index 0000000..6fe7e73 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/operations.md @@ -0,0 +1,357 @@ +# Operations Reference + +## Contents +- [Generated Fields](#generated-fields) +- [Queries](#queries) +- [Mutations](#mutations) +- [Key Scalars](#key-scalars) +- [Multi-Step Operations](#multi-step-operations) + +--- + +## Generated Fields + +Data Connect auto-generates fields for each `@table` type: + +| Generated Field | Purpose | Example | +|-----------------|---------|---------| +| `movie(id: UUID, key: Key, first: Row)` | Get single record | `movie(id: $id)` or `movie(first: {where: ...})` | +| `movies(where: ..., orderBy: ..., limit: ..., offset: ..., distinct: ..., having: ...)` | List/filter records | `movies(where: {...})` | +| `movie_insert(data: ...)` | Create record | Returns key | +| `movie_insertMany(data: [...])` | Bulk create | Returns keys | +| `movie_update(id: ..., data: ...)` | Update by ID | Returns key or null | +| `movie_updateMany(where: ..., data: ...)` | Bulk update | Returns count | +| `movie_upsert(data: ...)` | Insert or update | Returns key | +| `movie_delete(id: ...)` | Delete by ID | Returns key or null | +| `movie_deleteMany(where: ...)` | Bulk delete | Returns count | + +### Relation Fields +For a `Post` with `author: User!`: +- `post.author` - Navigate to related User +- `user.posts_on_author` - Reverse: all Posts by User + +For many-to-many via `MovieActor`: +- `movie.actors_via_MovieActor` - Get all actors +- `actor.movies_via_MovieActor` - Get all movies + +--- + +## Queries + +### Basic Query + +```graphql +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre releaseYear + } +} +``` + +### List with Filtering + +```graphql +query ListMovies($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre }, + rating: { ge: $minRating } + }, + orderBy: [{ releaseYear: DESC }, { title: ASC }], + limit: 20, + offset: 0 + ) { + id title genre rating + } +} +``` + +### Filter Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `eq` | Equals | `{ title: { eq: "Matrix" }}` | +| `ne` | Not equals | `{ status: { ne: "deleted" }}` | +| `gt`, `ge` | Greater than (or equal) | `{ rating: { ge: 4 }}` | +| `lt`, `le` | Less than (or equal) | `{ releaseYear: { lt: 2000 }}` | +| `in` | In list | `{ genre: { in: ["Action", "Drama"] }}` | +| `nin` | Not in list | `{ status: { nin: ["deleted", "hidden"] }}` | +| `isNull` | Is null check | `{ description: { isNull: true }}` | +| `contains` | String contains | `{ title: { contains: "war" }}` | +| `startsWith` | String starts with | `{ title: { startsWith: "The" }}` | +| `endsWith` | String ends with | `{ email: { endsWith: "@gmail.com" }}` | +| `includes` | Array includes | `{ tags: { includes: "sci-fi" }}` | + +### Expression Operators (Compare with Server Values) + +Use `_expr` suffix to compare with server-side values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +query RecentPosts @auth(level: PUBLIC) { + posts(where: { publishedAt: { lt_expr: "request.time" }}) { + id title + } +} +``` + +### Logical Operators + +```graphql +query ComplexFilter($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies(where: { + _or: [ + { genre: { eq: $genre }}, + { rating: { ge: $minRating }} + ], + _and: [ + { releaseYear: { ge: 2000 }}, + { status: { ne: "hidden" }} + ], + _not: { genre: { eq: "Horror" }} + }) { id title } +} +``` + +### Relational Queries + +```graphql +# Navigate relationships +query MovieWithDetails($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + title + # One-to-one + metadata: movieMetadata_on_movie { director } + # One-to-many + reviews: reviews_on_movie { rating user { name }} + # Many-to-many + actors: actors_via_MovieActor { name } + } +} + +# Filter by related data +query MoviesByDirector($director: String!) @auth(level: PUBLIC) { + movies(where: { + movieMetadata_on_movie: { director: { eq: $director }} + }) { id title } +} +``` + +### Aliases + +```graphql +query CompareRatings($genre: String!) @auth(level: PUBLIC) { + highRated: movies(where: { genre: { eq: $genre }, rating: { ge: 8 }}) { + title rating + } + lowRated: movies(where: { genre: { eq: $genre }, rating: { lt: 5 }}) { + title rating + } +} +``` + +--- + +## Mutations + +### Create + +```graphql +mutation CreateMovie($title: String!, $genre: String) @auth(level: USER) { + movie_insert(data: { + title: $title, + genre: $genre + }) +} +``` + +### Create with Server Values + +```graphql +mutation CreatePost($title: String!, $content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", # Current user + id_expr: "uuidV4()", # Auto-generate UUID + createdAt_expr: "request.time", # Server timestamp + title: $title, + content: $content + }) +} +``` + +### Update + +```graphql +mutation UpdateMovie($id: UUID!, $title: String, $genre: String) @auth(level: USER) { + movie_update( + id: $id, + data: { + title: $title, + genre: $genre, + updatedAt_expr: "request.time" + } + ) +} +``` + +### Update Operators + +```graphql +mutation IncrementViews($id: UUID!) @auth(level: PUBLIC) { + movie_update(id: $id, data: { + viewCount_update: { inc: 1 } + }) +} + +mutation AddTag($id: UUID!, $tag: String!) @auth(level: USER) { + movie_update(id: $id, data: { + tags_update: { add: [$tag] } # add, remove, append, prepend + }) +} +``` + +| Operator | Types | Description | +|----------|-------|-------------| +| `inc` | Int, Float, Date, Timestamp | Increment value | +| `dec` | Int, Float, Date, Timestamp | Decrement value | +| `add` | Lists | Add items if not present | +| `remove` | Lists | Remove all matching items | +| `append` | Lists | Append to end | +| `prepend` | Lists | Prepend to start | + +### Upsert + +```graphql +mutation UpsertUser($email: String!, $name: String!) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid", + email: $email, + name: $name + }) +} +``` + +### Delete + +```graphql +mutation DeleteMovie($id: UUID!) @auth(level: USER) { + movie_delete(id: $id) +} + +mutation DeleteOldDrafts @auth(level: USER) { + post_deleteMany(where: { + status: { eq: "draft" }, + createdAt: { lt_time: { now: true, sub: { days: 30 }}} + }) +} +``` + +### Filtered Updates/Deletes (User-Owned) + +```graphql +mutation UpdateMyPost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } # Only own posts + }}, + data: { content: $content } + ) +} +``` + +--- + +## Key Scalars + +Key scalars (`Movie_Key`, `User_Key`) are auto-generated types representing primary keys: + +```graphql +# Using key scalar +query GetMovie($key: Movie_Key!) @auth(level: PUBLIC) { + movie(key: $key) { title } +} + +# Variable format +# { "key": { "id": "uuid-here" } } + +# Composite key +# { "key": { "movieId": "...", "userId": "..." } } +``` + +Key scalars are returned by mutations: + +```graphql +mutation CreateAndFetch($title: String!) @auth(level: USER) { + key: movie_insert(data: { title: $title }) + # Returns: { "key": { "id": "generated-uuid" } } +} +``` + +--- + +## Multi-Step Operations + +### @transaction + +Ensures atomicity - all steps succeed or all rollback: + +```graphql +mutation CreateUserWithProfile($name: String!, $bio: String!) + @auth(level: USER) + @transaction { + # Step 1: Create user + user_insert(data: { + uid_expr: "auth.uid", + name: $name + }) + # Step 2: Create profile (uses response from step 1) + userProfile_insert(data: { + userId_expr: "response.user_insert.uid", + bio: $bio + }) +} +``` + +### Using response Binding + +Access results from previous steps: + +```graphql +mutation CreateTodoWithItem($listName: String!, $itemText: String!) + @auth(level: USER) + @transaction { + todoList_insert(data: { + id_expr: "uuidV4()", + name: $listName + }) + todoItem_insert(data: { + listId_expr: "response.todoList_insert.id", # From previous step + text: $itemText + }) +} +``` + +### Embedded Queries + +Run queries within mutations for validation: + +```graphql +mutation AddToPublicList($listId: UUID!, $item: String!) + @auth(level: USER) + @transaction { + # Step 1: Verify list exists and is public + query @redact { + todoList(id: $listId) @check(expr: "this != null", message: "List not found") { + isPublic @check(expr: "this == true", message: "List is not public") + } + } + # Step 2: Add item + todoItem_insert(data: { listId: $listId, text: $item }) +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/schema.md b/.agents/skills/firebase-data-connect/reference/schema.md new file mode 100644 index 0000000..21d34ec --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/schema.md @@ -0,0 +1,278 @@ +# Schema Reference + +## Contents +- [Defining Types](#defining-types) +- [Core Directives](#core-directives) +- [Relationships](#relationships) +- [Data Types](#data-types) +- [Enumerations](#enumerations) + +--- + +## Defining Types + +Types with `@table` map to PostgreSQL tables. Data Connect auto-generates an implicit `id: UUID!` primary key. + +```graphql +type Movie @table { + # id: UUID! is auto-added + title: String! + releaseYear: Int + genre: String +} +``` + +### Customizing Tables + +```graphql +type Movie @table(name: "movies", key: "id", singular: "movie", plural: "movies") { + id: UUID! @col(name: "movie_id") @default(expr: "uuidV4()") + title: String! + releaseYear: Int @col(name: "release_year") + genre: String @col(dataType: "varchar(20)") +} +``` + +### User Table with Auth + +```graphql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String @col(dataType: "varchar(100)") + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +--- + +## Core Directives + +### @table +Defines a database table. + +| Argument | Description | +|----------|-------------| +| `name` | PostgreSQL table name (snake_case default) | +| `key` | Primary key field(s), default `["id"]` | +| `singular` | Singular name for generated fields | +| `plural` | Plural name for generated fields | + +### @col +Customizes column mapping. + +| Argument | Description | +|----------|-------------| +| `name` | Column name in PostgreSQL | +| `dataType` | PostgreSQL type: `serial`, `varchar(n)`, `text`, etc. | +| `size` | Required for `Vector` type | + +### @default +Sets default value for inserts. + +| Argument | Description | +|----------|-------------| +| `value` | Literal value: `@default(value: "draft")` | +| `expr` | CEL expression: `@default(expr: "uuidV4()")`, `@default(expr: "auth.uid")`, `@default(expr: "request.time")` | +| `sql` | Raw SQL: `@default(sql: "now()")` | + +**Common expressions:** +- `uuidV4()` - Generate UUID +- `auth.uid` - Current user's Firebase Auth UID +- `request.time` - Server timestamp + +### @unique +Adds unique constraint. + +```graphql +type User @table { + email: String! @unique +} + +# Composite unique +type Review @table @unique(fields: ["movie", "user"]) { + movie: Movie! + user: User! + rating: Int +} +``` + +### @index +Creates database index for query performance. + +```graphql +type Movie @table @index(fields: ["genre", "releaseYear"], order: [ASC, DESC]) { + title: String! @index + genre: String + releaseYear: Int +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Fields for composite index (on @table) | +| `order` | `[ASC]` or `[DESC]` for each field | +| `type` | `BTREE` (default), `GIN` (arrays), `HNSW`/`IVFFLAT` (vectors) | + +### @searchable +Enables full-text search on String fields. + +```graphql +type Post @table { + title: String! @searchable + body: String! @searchable(language: "english") +} + +# Usage +query SearchPosts($q: String!) @auth(level: PUBLIC) { + posts_search(query: $q) { id title body } +} +``` + +--- + +## Relationships + +### One-to-Many (Implicit Foreign Key) + +```graphql +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! # Creates authorId foreign key + title: String! +} + +type User @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + # Auto-generated: posts_on_author: [Post!]! +} +``` + +### @ref Directive +Customizes foreign key reference. + +```graphql +type Post @table { + author: User! @ref(fields: "authorId", references: "id") + authorId: UUID! # Explicit FK field +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Local FK field name(s) | +| `references` | Target field(s) in referenced table | +| `constraintName` | PostgreSQL constraint name | + +**Cascade behavior:** +- Required reference (`User!`): CASCADE DELETE (post deleted when user deleted) +- Optional reference (`User`): SET NULL (authorId set to null when user deleted) + +### One-to-One + +Use `@unique` on the reference field: + +```graphql +type User @table { id: UUID! name: String! } + +type UserProfile @table { + user: User! @unique # One profile per user + bio: String + avatarUrl: String +} + +# Query: user.userProfile_on_user +``` + +### Many-to-Many + +Use a join table with composite primary key: + +```graphql +type Movie @table { id: UUID! title: String! } +type Actor @table { id: UUID! name: String! } + +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # Extra data on relationship +} + +# Generated fields: +# - movie.actors_via_MovieActor: [Actor!]! +# - actor.movies_via_MovieActor: [Movie!]! +# - movie.movieActors_on_movie: [MovieActor!]! +``` + +--- + +## Data Types + +| GraphQL Type | PostgreSQL Default | Other PostgreSQL Types | +|--------------|-------------------|----------------------| +| `String` | `text` | `varchar(n)`, `char(n)` | +| `Int` | `int4` | `int2`, `serial` | +| `Int64` | `bigint` | `bigserial`, `numeric` | +| `Float` | `float8` | `float4`, `numeric` | +| `Boolean` | `boolean` | | +| `UUID` | `uuid` | | +| `Date` | `date` | | +| `Timestamp` | `timestamptz` | Stored as UTC | +| `Any` | `jsonb` | | +| `Vector` | `vector` | Requires `@col(size: N)` | +| `[Type]` | Array | e.g., `[String]` → `text[]` | + +--- + +## Enumerations + +```graphql +enum Status { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + status: Status! @default(value: DRAFT) + allowedStatuses: [Status!] +} +``` + +**Rules:** +- Enum names: PascalCase, no underscores +- Enum values: UPPER_SNAKE_CASE +- Values are ordered (for comparison operations) +- Changing order or removing values is a breaking change + +--- + +## Views (Advanced) + +Map custom SQL queries to GraphQL types: + +```graphql +type MovieStats @view(sql: """ + SELECT + movie_id, + COUNT(*) as review_count, + AVG(rating) as avg_rating + FROM review + GROUP BY movie_id +""") { + movie: Movie @unique + reviewCount: Int + avgRating: Float +} + +# Query movies with stats +query TopMovies @auth(level: PUBLIC) { + movies(orderBy: [{ rating: DESC }]) { + title + stats: movieStats_on_movie { + reviewCount avgRating + } + } +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/sdks.md b/.agents/skills/firebase-data-connect/reference/sdks.md new file mode 100644 index 0000000..9885056 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/sdks.md @@ -0,0 +1,287 @@ +# SDK Reference + +## Contents +- [SDK Generation](#sdk-generation) +- [Web SDK](#web-sdk) +- [Android SDK](#android-sdk) +- [iOS SDK](#ios-sdk) +- [Admin SDK](#admin-sdk) + +--- + +## SDK Generation + +Configure SDK generation in `connector.yaml`: + +```yaml +connectorId: my-connector +generate: + javascriptSdk: + outputDir: "../web-app/src/lib/dataconnect" + package: "@movie-app/dataconnect" + kotlinSdk: + outputDir: "../android-app/app/src/main/kotlin/com/example/dataconnect" + package: "com.example.dataconnect" + swiftSdk: + outputDir: "../ios-app/DataConnect" +``` + +Generate SDKs: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` + +--- + +## Web SDK + +### Installation + +```bash +npm install firebase +``` + +### Initialization + +```typescript +import { initializeApp } from 'firebase/app'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@movie-app/dataconnect'; + +const app = initializeApp(firebaseConfig); +const dc = getDataConnect(app, connectorConfig); + +// For local development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dc, 'localhost', 9399); +} +``` + +### Calling Operations + +```typescript +// Generated SDK provides typed functions +import { listMovies, createMovie, getMovie } from '@movie-app/dataconnect'; + +// Accessing Nested Fields +const movie = await getMovie({ id: '...' }); +// Relations are just properties on the object +const director = movie.data.movie.metadata.director; +const firstActor = movie.data.movie.actors[0].name; + +// Query +const result = await listMovies(); +console.log(result.data.movies); + +// Query with variables +const movie = await getMovie({ id: 'uuid-here' }); + +// Mutation +const newMovie = await createMovie({ + title: 'New Movie', + genre: 'Action' +}); +console.log(newMovie.data.movie_insert); // Returns key +``` + +### Subscriptions + +```typescript +import { listMoviesRef, subscribe } from '@movie-app/dataconnect'; + +const unsubscribe = subscribe(listMoviesRef(), { + onNext: (result) => { + console.log('Movies updated:', result.data.movies); + }, + onError: (error) => { + console.error('Subscription error:', error); + } +}); + +// Later: unsubscribe(); +``` + +### With Authentication + +```typescript +import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; + +const auth = getAuth(app); +await signInWithEmailAndPassword(auth, email, password); + +// SDK automatically includes auth token in requests +const myReviews = await myReviews(); // @auth(level: USER) query from examples.md +``` + +--- + +## Android SDK + +### Dependencies (build.gradle.kts) + +```kotlin +dependencies { + implementation(platform("com.google.firebase:firebase-bom:33.0.0")) + implementation("com.google.firebase:firebase-dataconnect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.0") +} +``` + +### Initialization + +```kotlin +import com.google.firebase.Firebase +import com.google.firebase.dataconnect.dataConnect +import com.example.dataconnect.MyConnector + +val connector = MyConnector.instance + +// For emulator +connector.dataConnect.useEmulator("10.0.2.2", 9399) +``` + +### Calling Operations + +```kotlin +// Query +val result = connector.listMovies.execute() +result.data.movies.forEach { movie -> + println(movie.title) + // Access nested fields directly + println(movie.metadata?.director) + println(movie.actors.firstOrNull()?.name) +} + +// Query with variables +val movie = connector.getMovie.execute(id = "uuid-here") + +// Mutation +val newMovie = connector.createMovie.execute( + title = "New Movie", + genre = "Action" +) +``` + +### Flow Subscription + +```kotlin +connector.listMovies.flow().collect { result -> + when (result) { + is DataConnectResult.Success -> updateUI(result.data.movies) + is DataConnectResult.Error -> showError(result.exception) + } +} +``` + +--- + +## iOS SDK + +### Dependencies (Package.swift or SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "11.0.0") +] +// Add FirebaseDataConnect to target dependencies +``` + +### Initialization + +```swift +import FirebaseCore +import FirebaseDataConnect + +FirebaseApp.configure() +let connector = MyConnector.shared + +// For emulator +connector.useEmulator(host: "localhost", port: 9399) +``` + +### Calling Operations + +```swift +// Query +let result = try await connector.listMovies.execute() +for movie in result.data.movies { + print(movie.title) + // Access nested fields directly + print(movie.metadata?.director ?? "Unknown") + print(movie.actors.first?.name ?? "No actors") +} + +// Query with variables +let movie = try await connector.getMovie.execute(id: "uuid-here") + +// Mutation +let newMovie = try await connector.createMovie.execute( + title: "New Movie", + genre: "Action" +) +``` + +### Combine Publisher + +```swift +connector.listMovies.publisher + .sink( + receiveCompletion: { completion in + if case .failure(let error) = completion { + print("Error: \(error)") + } + }, + receiveValue: { result in + self.movies = result.data.movies + } + ) + .store(in: &cancellables) +``` + +--- + + + +## Admin SDK + +Server-side operations with elevated privileges (bypasses @auth): + +### Node.js + +```typescript +import { initializeApp, cert } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +initializeApp({ + credential: cert(serviceAccount) +}); + +const dc = getDataConnect(); + +// Execute operations (bypasses @auth) +const result = await dc.executeGraphql({ + query: `query { users { id email } }`, + operationName: 'ListAllUsers' +}); + +// Or use generated Admin SDK +import { listAllUsers } from './admin-connector'; +const users = await listAllUsers(); +``` + +### Generate Admin SDK + +In `connector.yaml`: + +```yaml +generate: + nodeAdminSdk: + outputDir: "./admin-sdk" + package: "@app/admin-dataconnect" +``` + +Generate: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` diff --git a/.agents/skills/firebase-data-connect/reference/security.md b/.agents/skills/firebase-data-connect/reference/security.md new file mode 100644 index 0000000..5eacee8 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/security.md @@ -0,0 +1,289 @@ +# Security Reference + +## Contents +- [@auth Directive](#auth-directive) +- [Access Levels](#access-levels) +- [CEL Expressions](#cel-expressions) +- [@check and @redact](#check-and-redact) +- [Authorization Patterns](#authorization-patterns) +- [Anti-Patterns](#anti-patterns) + +--- + +## @auth Directive + +Every deployable query/mutation must have `@auth`. Without it, operations default to `NO_ACCESS`. + +```graphql +query PublicData @auth(level: PUBLIC) { ... } +query UserData @auth(level: USER) { ... } +query AdminOnly @auth(expr: "auth.token.admin == true") { ... } +``` + +| Argument | Description | +|----------|-------------| +| `level` | Preset access level | +| `expr` | CEL expression (alternative to level) | +| `insecureReason` | Suppress deploy warning for PUBLIC/unfiltered USER | + +--- + +## Access Levels + +| Level | Who Can Access | CEL Equivalent | +|-------|----------------|----------------| +| `PUBLIC` | Anyone, authenticated or not | `true` | +| `USER_ANON` | Any authenticated user (including anonymous) | `auth.uid != nil` | +| `USER` | Authenticated users (excludes anonymous) | `auth.uid != nil && auth.token.firebase.sign_in_provider != 'anonymous'` | +| `USER_EMAIL_VERIFIED` | Users with verified email | `auth.uid != nil && auth.token.email_verified` | +| `NO_ACCESS` | Admin SDK only | `false` | + +> **Important:** Levels like `USER` are starting points. Always add filters or expressions to verify the user can access specific data. + +--- + +## CEL Expressions + +### Available Bindings + +| Binding | Description | +|---------|-------------| +| `auth.uid` | Current user's Firebase UID | +| `auth.token` | Auth token claims (see below) | +| `vars` | Operation variables (e.g., `vars.movieId`) | +| `request.time` | Server timestamp | +| `request.operationName` | "query" or "mutation" | + +### auth.token Fields + +| Field | Description | +|-------|-------------| +| `email` | User's email address | +| `email_verified` | Boolean: email verified | +| `phone_number` | User's phone | +| `name` | Display name | +| `sub` | Firebase UID (same as auth.uid) | +| `firebase.sign_in_provider` | `password`, `google.com`, `anonymous`, etc. | +| `` | Custom claims set via Admin SDK | + +### Expression Examples + +```graphql +# Check custom claim +@auth(expr: "auth.token.role == 'admin'") + +# Check verified email domain +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") + +# Check multiple conditions +@auth(expr: "auth.uid != nil && (auth.token.role == 'editor' || auth.token.role == 'admin')") + +# Check variable +@auth(expr: "has(vars.status) && vars.status in ['draft', 'published']") +``` + +### Using eq_expr in Filters + +Compare database fields with auth values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +mutation UpdateMyPost($id: UUID!, $title: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id }, + authorUid: { eq_expr: "auth.uid" } + }}, + data: { title: $title } + ) +} +``` + +--- + +## @check and @redact + +Use `@check` to validate data and `@redact` to hide results from client: + +### @check +Validates a field value; aborts if check fails. + +```graphql +@check(expr: "this != null", message: "Not found") +@check(expr: "this == 'editor'", message: "Must be editor") +@check(expr: "this.exists(p, p.role == 'admin')", message: "No admin found") +``` + +| Argument | Description | +|----------|-------------| +| `expr` | CEL expression; `this` = current field value | +| `message` | Error message if check fails | +| `optional` | If `true`, pass when field not present | + +### @redact +Hides field from response (still evaluated for @check): + +```graphql +query @redact { ... } # Query result hidden but @check still runs +``` + +### Authorization Data Lookup + +Check database permissions before allowing mutation: + +```graphql +mutation UpdateMovie($id: UUID!, $title: String!) + @auth(level: USER) + @transaction { + # Step 1: Check user has permission + query @redact { + moviePermission( + key: { movieId: $id, userId_expr: "auth.uid" } + ) @check(expr: "this != null", message: "No access to movie") { + role @check(expr: "this == 'editor'", message: "Must be editor") + } + } + # Step 2: Update if authorized + movie_update(id: $id, data: { title: $title }) +} +``` + +### Validate Key Exists + +```graphql +mutation MustDeleteMovie($id: UUID!) @auth(level: USER) @transaction { + movie_delete(id: $id) + @check(expr: "this != null", message: "Movie not found") +} +``` + +--- + +## Authorization Patterns + +### User-Owned Resources + +```graphql +# Create with owner +mutation CreatePost($content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", + content: $content + }) +} + +# Read own data only +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id content + } +} + +# Update own data only +mutation UpdatePost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}}, + data: { content: $content } + ) +} + +# Delete own data only +mutation DeletePost($id: UUID!) @auth(level: USER) { + post_delete( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}} + ) +} +``` + +### Role-Based Access + +```graphql +# Admin-only query +query AllUsers @auth(expr: "auth.token.admin == true") { + users { id email name } +} + +# Role from database +mutation AdminAction($id: UUID!) @auth(level: USER) @transaction { + query @redact { + user(key: { uid_expr: "auth.uid" }) { + role @check(expr: "this == 'admin'", message: "Admin required") + } + } + # ... admin action +} +``` + +### Public Data with Filters + +```graphql +query PublicPosts @auth(level: PUBLIC) { + posts(where: { + visibility: { eq: "public" }, + publishedAt: { lt_expr: "request.time" } + }) { + id title content + } +} +``` + +### Tiered Access (Pro Content) + +```graphql +query ProContent @auth(expr: "auth.token.plan == 'pro'") { + posts(where: { visibility: { in: ["public", "pro"] }}) { + id title content + } +} +``` + +--- + +## Anti-Patterns + +### ❌ Don't Pass User ID as Variable + +```graphql +# BAD - any user can pass any userId +query GetUserPosts($userId: String!) @auth(level: USER) { + posts(where: { authorUid: { eq: $userId }}) { ... } +} + +# GOOD - use auth.uid +query GetMyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Use USER Without Filters + +```graphql +# BAD - any authenticated user sees all documents +query AllDocs @auth(level: USER) { + documents { id title content } +} + +# GOOD - filter to user's documents +query MyDocs @auth(level: USER) { + documents(where: { ownerId: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Trust Unverified Email + +```graphql +# BAD - email not verified +@auth(expr: "auth.token.email.endsWith('@company.com')") + +# GOOD - verify email first +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") +``` + +### ❌ Don't Use PUBLIC/USER for Prototyping + +During development, set operations to `NO_ACCESS` until you implement proper authorization. Use emulator and VS Code extension for testing. diff --git a/.agents/skills/firebase-data-connect/templates.md b/.agents/skills/firebase-data-connect/templates.md new file mode 100644 index 0000000..75d20dc --- /dev/null +++ b/.agents/skills/firebase-data-connect/templates.md @@ -0,0 +1,269 @@ +# Templates + +Ready-to-use templates for common Firebase Data Connect patterns. + +--- + +## Basic CRUD Schema + +```graphql +# schema.gql +type Item @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + description: String + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query ListItems @auth(level: PUBLIC) { + items(orderBy: [{ createdAt: DESC }]) { + id name description createdAt + } +} + +query GetItem($id: UUID!) @auth(level: PUBLIC) { + item(id: $id) { id name description createdAt updatedAt } +} +``` + +```graphql +# mutations.gql +mutation CreateItem($name: String!, $description: String) @auth(level: USER) { + item_insert(data: { name: $name, description: $description }) +} + +mutation UpdateItem($id: UUID!, $name: String, $description: String) @auth(level: USER) { + item_update(id: $id, data: { + name: $name, + description: $description, + updatedAt_expr: "request.time" + }) +} + +mutation DeleteItem($id: UUID!) @auth(level: USER) { + item_delete(id: $id) +} +``` + +--- + +## User-Owned Resources + +```graphql +# schema.gql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String +} + +type Note @table { + id: UUID! @default(expr: "uuidV4()") + owner: User! + title: String! + content: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query MyNotes @auth(level: USER) { + notes( + where: { owner: { uid: { eq_expr: "auth.uid" }}}, + orderBy: [{ createdAt: DESC }] + ) { id title content createdAt } +} + +query GetMyNote($id: UUID!) @auth(level: USER) { + note( + first: { where: { + id: { eq: $id }, + owner: { uid: { eq_expr: "auth.uid" }} + }} + ) { id title content } +} +``` + +```graphql +# mutations.gql +mutation CreateNote($title: String!, $content: String) @auth(level: USER) { + note_insert(data: { + owner: { uid_expr: "auth.uid" }, + title: $title, + content: $content + }) +} + +mutation UpdateNote($id: UUID!, $title: String, $content: String) @auth(level: USER) { + note_update( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}}, + data: { title: $title, content: $content } + ) +} + +mutation DeleteNote($id: UUID!) @auth(level: USER) { + note_delete( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}} + ) +} +``` + +--- + +## Many-to-Many Relationship + +```graphql +# schema.gql +type Tag @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @unique +} + +type Article @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + content: String! +} + +type ArticleTag @table(key: ["article", "tag"]) { + article: Article! + tag: Tag! +} +``` + +```graphql +# queries.gql +query ArticlesByTag($tagName: String!) @auth(level: PUBLIC) { + articles(where: { + articleTags_on_article: { tag: { name: { eq: $tagName }}} + }) { + id title + tags: tags_via_ArticleTag { name } + } +} + +query ArticleWithTags($id: UUID!) @auth(level: PUBLIC) { + article(id: $id) { + id title content + tags: tags_via_ArticleTag { id name } + } +} +``` + +```graphql +# mutations.gql +mutation AddTagToArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_insert(data: { + article: { id: $articleId }, + tag: { id: $tagId } + }) +} + +mutation RemoveTagFromArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_delete(key: { articleId: $articleId, tagId: $tagId }) +} +``` + +--- + +## dataconnect.yaml Template + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +--- + +## connector.yaml Template + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" + dartSdk: + outputDir: "../flutter/lib/dataconnect" + package: myapp_dataconnect +``` + +--- + +## Firebase Init Commands + +```bash +# Initialize Data Connect in project +npx -y firebase-tools@latest init dataconnect + +# Initialize with specific project +npx -y firebase-tools@latest use +npx -y firebase-tools@latest init dataconnect + +# Start emulator for development +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +--- + +## SDK Initialization (Web) + +```typescript +// lib/firebase.ts +import { initializeApp } from 'firebase/app'; +import { getAuth } from 'firebase/auth'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@myapp/dataconnect'; + +const firebaseConfig = { + apiKey: "...", + authDomain: "...", + projectId: "...", +}; + +export const app = initializeApp(firebaseConfig); +export const auth = getAuth(app); +export const dataConnect = getDataConnect(app, connectorConfig); + +// Connect to emulator in development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dataConnect, 'localhost', 9399); +} +``` + +```typescript +// Example usage +import { listItems, createItem } from '@myapp/dataconnect'; + +// List items +const { data } = await listItems(); +console.log(data.items); + +// Create item (requires auth) +await createItem({ name: 'New Item', description: 'Description' }); +``` diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md new file mode 100644 index 0000000..1eeb40f --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md @@ -0,0 +1,31 @@ +--- +name: firebase-firestore-enterprise-native-mode +description: Comprehensive guide for Firestore enterprise native including provisioning, data model, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore Enterprise with the Native mode, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Enterprise Native Mode + +This skill provides a complete guide for getting started with Firestore Enterprise Native Mode, including provisioning, data model, security rules, and SDK usage. + +## Provisioning + +To set up Firestore Enterprise Native Mode in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Data Model + +To learn about Firestore data model and how to organize your data, see [data_model.md](references/data_model.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Firestore Enterprise Native Mode in your application code, see: +- [Web SDK Usage](references/web_sdk_usage.md) +- [Python SDK Usage](references/python_sdk_usage.md) + +## Indexes + +Indexes help improve query performance and speed up slow queries. For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md new file mode 100644 index 0000000..0fe42c0 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md @@ -0,0 +1,54 @@ +# Firestore Data Model Reference + +Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in **documents**, which are organized into **collections**. + +## Document Data Model + +Data in Firestore is organized into documents, collections, and subcollections. + +### Documents +A **document** is a lightweight record that contains fields, which map to values. Each document is identified by a name. A document can contain complex nested objects in addition to basic data types like strings, numbers, and booleans. Documents are limited to a maximum size of 1 MiB. + +Example document (e.g., in a `users` collection): +```json +{ + "first": "Ada", + "last": "Lovelace", + "born": 1815 +} +``` + +### Collections +Documents live in **collections**, which are containers for your documents. For example, you could have a `users` collection to contain your various users, each represented by a document. +* Collections can only contain documents. They cannot directly contain raw fields with values, and they cannot contain other collections. +* Documents within a collection can contain different fields. +* You don't need to "create" or "delete" collections explicitly. After you create the first document in a collection, the collection exists. If you delete all of the documents in a collection, the collection no longer exists. + +### Subcollections +Documents can contain subcollections natively. A subcollection is a collection associated with a specific document. +For example, a user document in the `users` collection could have a `messages` subcollection containing message documents exclusively for that user. This creates a powerful hierarchical data structure. + +Data path example: `users/user1/messages/message1` + +## Collection Group Support + +A **collection group** consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection. + +### Use Cases +Collection group queries are useful when you want to query across multiple subcollections that share the same organizational structure. + +For example, imagine an app with a `landmarks` collection where each landmark has a `reviews` subcollection. If you want to find all 5-star reviews across *all* landmarks, it would involve checking many separate `reviews` subcollections. With a collection group, you can perform a single query against the `reviews` collection group. + +### Examples + +**Standard Query** (Single Collection): +Find all 5-star reviews for a specific landmark. +```javascript +db.collection('landmarks/golden_gate_bridge/reviews').where('rating', '==', 5) +``` + +**Collection Group Query**: +Find all 5-star reviews across *all* landmarks. +```javascript +db.collectionGroup('reviews').where('rating', '==', 5) +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md new file mode 100644 index 0000000..f1031bd --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md @@ -0,0 +1,111 @@ +# Firestore Indexes Reference + +Indexes helps to improve query performance. Firestore Enterprise edition does not create any indexes by default. By default, Firestore Enterprise performs a full collection scan to find documents that match a query, which can be slow and expensive for large collections. To avoid this, you can create indexes to optimize your queries. + +## Index Structure + +An index consists of the following: + +* a collection ID. +* a list of fields in the given collection. +* an order, either ascending or descending, for each field. + +### Index Ordering + +The order and sort direction of each field uniquely defines the index. For example, the following indexes are two distinct indexes and not interchangeable: + +* Field name `name` (ascending) and `population` (descending) +* Field name `name` (descending) and `population` (ascending) + +### Index Density + +Dense indexes: By default, Firestore indexes store data from all documents in a collection. An index entry will be added for a document regardless of whether the document contains any of the fields specified in the index. Non-existent fields are treated as having a NULL value when generating index entries. + +Sparse indexes: To change this behavior, you can define the index as a sparse index. A sparse index indexes only the documents in the collection that contain a value (including null) for at least one of the indexed fields. A sparse index reduces storage costs and can improve performance. + +### Unique Indexes + +You can use unique index option to enforce unique values for the indexed fields. For indexes on multiple fields, each combination of values must be unique across the index. The database rejects any update and insert operations that attempt to create index entries with duplicate values. + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Single-Field Index on field `a` | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Single-Field Index on field `a` | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Single-Field Index on field `a` and `b` | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** on field `tags` and `active` | + +If no indexes is present, Firestore Enterprise will perform a full collection scan to find documents that match a query. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +Define a dense index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "DENSE", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a sparse-any index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +Define a unique index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "density": "SPARSE_ANY", + "unique": true, + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx firebase-tools@latest -y deploy --only firestore:indexes +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md new file mode 100644 index 0000000..02a97e3 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md @@ -0,0 +1,101 @@ +# Provisioning Firestore Enterprise Native Mode + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create a Firestore Enterprise Database**: Create a Firestore Enterprise database using the Firebase CLI. +2. **Create `firebase.json`**: This file contains database configuration for the Firebase CLI. +3. **Create `firestore.rules`**: This file contains your security rules. +4. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create a Firestore Enterprise Database + +Use the following command to create a Firestore Enterprise database: + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" +``` + +This will create an enterprise database in `nam5` with native mode enabled. A database id is required to create an enterprise database and the database id must not be `(default)`. To enable realtime-updates feature, use `--realtime-updates` flag. + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" \ + --realtime-updates="ENABLED" +``` + +### 2. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "edition": "enterprise", + "database": "my-database-id", + "location": "nam5" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +firebase deploy --only firestore + +# To deploy just rules +firebase deploy --only firestore:rules + +# To deploy just indexes +firebase deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +firebase emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md new file mode 100644 index 0000000..8bd67a4 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md @@ -0,0 +1,126 @@ +# Python SDK Usage + +The Python Server SDK is used for backend/server environments and utilizes Google Application Default Credentials in most Google Cloud environments. + +### Writing Data + +#### Set a Document +Creates a document if it does not exist or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```python +city_ref = db.collection("cities").document("LA") + +# Create/Overwrite +city_ref.set({ + "name": "Los Angeles", + "state": "CA", + "country": "USA" +}) + +# Merge +city_ref.set({"population": 3900000}, merge=True) +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```python +update_time, city_ref = db.collection("cities").add({ + "name": "Tokyo", + "country": "Japan" +}) +print("Document written with ID: ", city_ref.id) +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```python +city_ref = db.collection("cities").document("LA") +city_ref.update({ + "capital": True +}) +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```python +from google.cloud.firestore import Transaction + +transaction = db.transaction() +city_ref = db.collection("cities").document("SF") + +@firestore.transactional +def update_in_transaction(transaction, city_ref): + snapshot = city_ref.get(transaction=transaction) + if not snapshot.exists: + raise Exception("Document does not exist!") + + new_population = snapshot.get("population") + 1 + transaction.update(city_ref, {"population": new_population}) + +update_in_transaction(transaction, city_ref) +``` + +### Reading Data + +#### Get a Single Document + +```python +doc_ref = db.collection("cities").document("SF") +doc = doc_ref.get() + +if doc.exists: + print(f"Document data: {doc.to_dict()}") +else: + print("No such document!") +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```python +docs = db.collection("cities").stream() + +for doc in docs: + print(f"{doc.id} => {doc.to_dict()}") +``` + +### Queries + +#### Simple and Compound Queries +Use `.where()` to combine filters safely. Stack `.where()` calls for compound queries. + +```python +from google.cloud.firestore import FieldFilter + +cities_ref = db.collection("cities") + +# Simple equality +query_1 = cities_ref.where(filter=FieldFilter("state", "==", "CA")) + +# Compound (AND) +query_2 = cities_ref.where( + filter=FieldFilter("state", "==", "CA") +).where( + filter=FieldFilter("population", ">", 1000000) +) +``` + +#### Order and Limit +Sort and limit results cleanly. + +```python +query = cities_ref.order_by("name").limit(3) +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```python +pipeline = client.pipeline().collection("users") +for result in pipeline.execute(): + print(f"{result.id} => {result.data()}") +``` diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md new file mode 100644 index 0000000..1eee422 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md @@ -0,0 +1,201 @@ +# Web SDK Usage + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +### Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'firebase apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); +``` + +### Writing Data + +#### Set a Document +Creates a document if it doesn't exist, or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +#### Add a Document with Auto-ID +Use when you don't care about the document ID and want Firestore to automatically generate one. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +### Reading Data + +#### Get a Single Document + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + console.log(doc.id, " => ", doc.data()); +}); +``` + +### Realtime Updates + +#### Listen to a Document or Query + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// To stop listening: +// unsub(); +``` + +### Handle Changes + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +### Queries + +#### Simple and Compound Queries +Use `query()` and `where()` to combine filters safely. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires a composite index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +#### Order and Limit +Sort and limit results cleanly. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```javascript + +const readDataPipeline = db.pipeline() + .collection("users"); + +// Execute the pipeline and handle the result +try { + const querySnapshot = await execute(readDataPipeline); + querySnapshot.results.forEach((result) => { + console.log(`${result.id} => ${result.data()}`); + }); +} catch (error) { + console.error("Error getting documents: ", error); +} +``` diff --git a/.agents/skills/firebase-firestore-standard/SKILL.md b/.agents/skills/firebase-firestore-standard/SKILL.md new file mode 100644 index 0000000..0eb6c2e --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/SKILL.md @@ -0,0 +1,27 @@ +--- +name: firebase-firestore-standard +description: Comprehensive guide for Firestore Standard Edition, including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Firestore Standard Edition + +This skill provides a complete guide for getting started with Cloud Firestore Standard Edition, including provisioning, securing, and integrating it into your application. + +## Provisioning + +To set up Cloud Firestore in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Cloud Firestore in your application code, choose your platform: + +* **Web (Modular SDK)**: [web_sdk_usage.md](references/web_sdk_usage.md) + +## Indexes + +For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-standard/references/indexes.md b/.agents/skills/firebase-firestore-standard/references/indexes.md new file mode 100644 index 0000000..7623eb8 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/indexes.md @@ -0,0 +1,82 @@ +# Firestore Indexes Reference + +Indexes allow Firestore to ensure that query performance depends on the size of the result set, not the size of the database. + +## Index Types + +### Single-Field Indexes +In Standard Edition, Firestore **automatically creates** a single-field index for every field in a document (and subfields in maps). +* **Support**: Simple equality queries (`==`) and single-field range/sort queries (`<`, `<=`, `orderBy`). +* **Behavior**: You generally don't need to manage these unless you want to *exempt* a field. + +### Composite Indexes +A composite index stores a sorted mapping of all documents based on an ordered list of fields. +* **Support**: Complex queries that filter or sort by **multiple fields**. +* **Creation**: These are **NOT** automatically created. You must define them manually or via the console/CLI. + +## Automatic vs. Manual Management + +### What is Automatic? +* Indexes for simple queries. +* Merging of single-field indexes for multiple equality filters (e.g., `where("state", "==", "CA").where("country", "==", "USA")`). + +### When Do I Need to Act? +If you attempt a query that requires a composite index, the SDK will throw an error containing a **direct link** to the Firebase Console to create that specific index. + +**Example Error:** +> "The query requires an index. You can create it here: https://console.firebase.google.com/project/..." + +## Query Support Examples + +| Query Type | Index Required | +| :--- | :--- | +| **Simple Equality**
`where("a", "==", 1)` | Automatic (Single-Field) | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Automatic (Single-Field) | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Automatic (Merged Single-Field) | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** (and technically limited query support) | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** | + +## Best Practices & Exemptions + +You can **exempt** fields from automatic indexing to save storage or strictly enforce write limits. + +### 1. High Write Rates (Sequential Values) +* **Problem**: Indexing fields that increase sequentially (like `timestamp`) limits the write rate to ~500 writes/second per collection. +* **Solution**: If you don't query on this field, **exempt** it from simple indexing. + +### 2. Large String/Map/Array Fields +* **Problem**: Indexing limits (40k entries per doc). Indexing large blobs wastes storage. +* **Solution**: Exempt large text blobs or huge arrays if they aren't used for filtering. + +### 3. TTL Fields +* **Problem**: TTL (Time-To-Live) deletion can cause index churn. +* **Solution**: Exempt the TTL timestamp field from indexing if you don't query it. + +## Management + +### Config files +Your indexes should be defined in `firestore.indexes.json` (pointed to by `firebase.json`). + +```json +{ + "indexes": [ + { + "collectionGroup": "cities", + "queryScope": "COLLECTION", + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" }, + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ], + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: +```bash +npx -y firebase-tools@latest deploy --only firestore:indexes +``` diff --git a/.agents/skills/firebase-firestore-standard/references/provisioning.md b/.agents/skills/firebase-firestore-standard/references/provisioning.md new file mode 100644 index 0000000..5278801 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/provisioning.md @@ -0,0 +1,87 @@ +# Provisioning Cloud Firestore + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx -y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create `firebase.json`**: This file configures the Firebase CLI. +2. **Create `firestore.rules`**: This file contains your security rules. +3. **Create `firestore.indexes.json`**: This file contains your index definitions. + +### 1. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json" + } +} +``` + +This will use the default database with the Standard edition. To use a different database, specify the database ID and location. You can check the list of available databases using `npx -y firebase-tools@latest firestore:databases:list`. If the database does not exist, it will be created when you deploy: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "database": "my-database-id", + "location": "us-central1" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to start: + +```json +{ + "indexes": [], + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + + +## Deploy rules and indexes +```bash +# To deploy all rules and indexes +npx -y firebase-tools@latest deploy --only firestore + +# To deploy just rules +npx -y firebase-tools@latest deploy --only firestore:rules + +# To deploy just indexes +npx -y firebase-tools@latest deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +npx -y firebase-tools@latest emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact with it using the Emulator UI (usually at http://localhost:4000/firestore). diff --git a/.agents/skills/firebase-firestore-standard/references/security_rules.md b/.agents/skills/firebase-firestore-standard/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/security_rules.md @@ -0,0 +1,414 @@ +## 1. Generate Firestore Rules +You are an expert Firebase Security Rules engineer with deep knowledge of Firestore security best practices. Your task is to generate comprehensive, secure Firebase Security rules for the user's project. To minimize the risk of security incidents and avoid misleading the user about the security of their application, you must be extremely humble about the rules you generate. Always present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly like this: +"I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for . However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and `limit()` clause. The security rules **MUST** allow these specific queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs, emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described in the "Critical Directives" section below. This involves defining a specific validation function (e.g., `isValidUser`) and calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after the operation, the required fields are still available and that the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly readable, always require authentication for any access to data unless + the user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any "allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +2. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + - Firestore security rules apply to the entire document. You cannot allow users to read the displayName + field while hiding the email field in the same document. + - If a collection (e.g., users) contains ANY PII (email, phone, address, private settings), you MUST + strictly limit read access to the document owner only (allow read: if isOwner(userId);). + - If the application requires public profiles (e.g., showing user names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL) directly onto the resources + they create (e.g., store authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that contains only non-sensitive data, + and keep the sensitive data in a locked-down users_private collection. + - NEVER write a rule that allows read access to a document containing PII for anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines +This is one of the most important set of instructions to follow. Failing to follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that no user should be able to create an item in a database with their role set to +a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested action. +- **ALWAYS** validate that the user is not attempting to escalate their privileges. +- **ALWAYS** validate that the user is not attempting to access data they do not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex check like `isValidDateString` only validates **format**, not **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field that should not change after creation must be explicitly protected in `update` rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update specific fields (like incrementing a counter), you **MUST** explicitly verify that all other fields (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized metadata modification. For sensitive fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** strictly validate the type (string) and length (e.g. < 50 chars) to prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY `authorUid` and fetch the profile client-side. If you denormalize, you accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain any fields other than those explicitly defined in the data model. This prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable Information) to be exposed in the data model. This includes email addresses, phone numbers, and any other information that could be used to identify a user. For example, even if a user is logged-in, they should not have access to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating `allow read: if isAuthenticated();` for the users collection if that collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths that are protected with only `isAuthenticated()` do not need any additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is allowing updates based solely on ownership (e.g., `allow update: if isOwner(resource.data.uid);`). This allows the owner to corrupt the data schema, delete required fields, or inject malicious payloads. You **MUST** always combine ownership checks with data validation (e.g., `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. You **MUST** validate the contents of the array (e.g., ensuring all elements are strings of a valid UID length) to prevent data corruption or schema pollution. For example, a `tags` array must verify that every item is a string AND that each string is within a reasonable length (e.g., < 20 chars). +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`, `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner editors. In `update` rules, use `fieldUnchanged()` for these fields unless the `request.auth.uid` matches the document's original owner/creator. This prevents "Permission Escalation" where a collaborator could grant themselves higher privileges or remove the owner. + + +### Advanced Validation for Business Logic + + Secure rules must enforce the application's business logic. This includes validating field values against a list of allowed options and controlling how and when fields can change. + + #### 1. Enforce Enum Values + + If a field should only contain specific values (e.g., a status), validate against a list. + + **Example:** + + ```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... + ``` + + #### 2. Validate State Transitions + + For `update` operations, you **MUST** validate that a field is changing from a valid previous state to a valid new state. This prevents users from bypassing workflows (e.g., marking a task as 'completed' from 'archived'). + + **Example:** + + ```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... + ``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent document ID), you **MUST** ensure it is correctly scoped to the user or valid within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you **MUST** ensure: +1. **Atomic Increments:** The field is only changing by exactly +1 or -1. +2. **Isolation:** **NO OTHER FIELDS** are being modified. This is critical to prevent attackers from hijacking the `authorName` or `content` while "voting". +3. **Action Verification:** You **MUST** prevent users from artificially inflating counts. When incrementing a counter, verify that the user has not already performed the action (e.g., by checking for the existence of a 'like' document) and is not looping updates. + * **CRITICAL:** Relying solely on `!exists(likeDoc)` is insufficient because a malicious user can skip creating the document and loop the increment. + * **SOLUTION:** Use `getAfter()` to verify that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works after firestore rules updates. + +3. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you **MUST** enforce realistic size limits (e.g., `text.size() < 1000`, `tags.size() < 20`). **Failure to limit a single string field (like `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication and retrieve documents that should be private (e.g., where `visible == false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` it with a 1MB string or invalid fields? (Tests if validation logic is missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document and then `update` it into an invalid state (e.g., remove a required field, write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to any field that accepts a string or a massive array to a list field? Every string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin role by writing `isAdmin: true` to my user profile document? (Tests reliance on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from `'pending'` directly to `'completed'`, bypassing the required `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like `imageBucket` or `profilePic`) to a value that points to another user's data or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or `quantity`) to a negative number or an extremely large one? (Tests for range validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's users document? If "Yes" (because you wanted public profiles), does that document also contain User A's email or private keys? If both are true, the rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I increment it without creating the corresponding tracking document (e.g., inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app performs? (e.g., if the app filters by `status == 'published'`, do the rules allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only ones) call the `isValidX()` function? If an `allow update` rule only checks `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints +1. **Never skip the devil's advocate phase** - this is your primary security validation +2. **MUST include helper functions** for common operations ('isAuthenticated', 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only firestore:rules --dry-run' or a similar tool before outputting the final file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the rules. +8. **Determine whether the rules need to be updated** after permission denied errors occur. +9. **Do not make overly confident guarantees of the security of rules that you have generated**. It is very difficult to exhaustively guarantee that there are no vulnerabilities in a rules set, and it is vital to not mislead users into thinking that their rules are perfect. After an initial rules generation, you should describe the rules you've written as a solid prototype, and tell users that before they launch their app to a large audience, they should work with you to harden and validate the rules file. Be clear that users should carefully review rules to ensure security. diff --git a/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md new file mode 100644 index 0000000..3d85134 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md @@ -0,0 +1,183 @@ +# Firestore Web SDK Usage Guide + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +## Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'npx -y firebase-tools@latest apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); + +``` + +## Writing Data + +### Set a Document (`setDoc`) +Creates a document if it doesn't exist, or overwrites it if it does. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +### Add a Document with Auto-ID (`addDoc`) +Use when you don't care about the document ID. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +### Update a Document (`updateDoc`) +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +## Reading Data + +### Get a Single Document (`getDoc`) + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +### Get Multiple Documents (`getDocs`) +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + // doc.data() is never undefined for query doc snapshots + console.log(doc.id, " => ", doc.data()); +}); +``` + +## Realtime Updates + +### Listen to a Document/Query (`onSnapshot`) + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// Stop listening +// unsub(); +``` + +### Handle Changes (Added/Modified/Removed) + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +## Queries + +### Simple and Compound Queries +Use `query()` to combine filters. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires an index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +### Order and Limit +Sort and limit results. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` diff --git a/.agents/skills/firebase-hosting-basics/SKILL.md b/.agents/skills/firebase-hosting-basics/SKILL.md new file mode 100644 index 0000000..a83ac28 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/SKILL.md @@ -0,0 +1,46 @@ +--- +name: firebase-hosting-basics +description: Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting. +--- + +# hosting-basics + +This skill provides instructions and references for working with Firebase Hosting, a fast and secure hosting service for your web app, static and dynamic content, and microservices. + +## Overview + +Firebase Hosting provides production-grade web content hosting for developers. With a single command, you can deploy web apps and serve both static and dynamic content to a global CDN (content delivery network). + +**Key Features:** +- **Fast Content Delivery:** Files are cached on SSDs at CDN edges around the world. +- **Secure by Default:** Zero-configuration SSL is built-in. +- **Preview Channels:** View and test changes on temporary preview URLs before deploying live. +- **GitHub Integration:** Automate previews and deploys with GitHub Actions. +- **Dynamic Content:** Serve dynamic content and microservices using Cloud Functions or Cloud Run. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Instructions + +### 1. Configuration (`firebase.json`) +For details on configuring Hosting behavior, including public directories, redirects, rewrites, and headers, see [configuration.md](references/configuration.md). + +### 2. Deploying +For instructions on deploying your site, using preview channels, and managing releases, see [deploying.md](references/deploying.md). + +### 3. Emulation +To test your app locally: +```bash +npx -y firebase-tools@latest emulators:start --only hosting +``` +This serves your app at `http://localhost:5000` by default. diff --git a/.agents/skills/firebase-hosting-basics/references/configuration.md b/.agents/skills/firebase-hosting-basics/references/configuration.md new file mode 100644 index 0000000..adb9050 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/configuration.md @@ -0,0 +1,101 @@ +# Hosting Configuration (`firebase.json`) + +The `hosting` section of `firebase.json` configures how your site is deployed and served. + +## Key Attributes + +### `public` (Required) +Specifies the directory to deploy to Firebase Hosting. +```json +"hosting": { + "public": "public" +} +``` + +### `ignore` (Optional) +Files to ignore on deploy. Uses glob patterns (like `.gitignore`). +**Default ignores:** `firebase.json`, `**/.*`, `**/node_modules/**` + +### `redirects` (Optional) +URL redirects to prevent broken links or shorten URLs. +```json +"redirects": [ + { + "source": "/foo", + "destination": "/bar", + "type": 301 + } +] +``` + +### `rewrites` (Optional) +Serve the same content for multiple URLs, useful for SPAs or Dynamic Content. +```json +"rewrites": [ + { + "source": "**", + "destination": "/index.html" + }, + { + "source": "/api/**", + "function": "apiFunction" + }, + { + "source": "/container/**", + "run": { + "serviceId": "helloworld", + "region": "us-central1" + } + } +] +``` + +### `headers` (Optional) +Custom response headers. +```json +"headers": [ + { + "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)", + "headers": [ + { + "key": "Access-Control-Allow-Origin", + "value": "*" + } + ] + } +] +``` + +### `cleanUrls` (Optional) +If `true`, drops `.html` extension from URLs. +```json +"cleanUrls": true +``` + +### `trailingSlash` (Optional) +Controls trailing slashes in static content URLs. +- `true`: Adds trailing slash. +- `false`: Removes trailing slash. + +## Full Example + +```json +{ + "hosting": { + "public": "dist", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ], + "cleanUrls": true, + "trailingSlash": false + } +} +``` diff --git a/.agents/skills/firebase-hosting-basics/references/deploying.md b/.agents/skills/firebase-hosting-basics/references/deploying.md new file mode 100644 index 0000000..df26c5e --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/deploying.md @@ -0,0 +1,39 @@ +# Deploying to Firebase Hosting + +## Standard Deployment +To deploy your Hosting content and configuration to your live site: + +```bash +npx -y firebase-tools@latest deploy --only hosting +``` + +This deploys to your default sites (`PROJECT_ID.web.app` and `PROJECT_ID.firebaseapp.com`). + +## Preview Channels +Preview channels allow you to test changes on a temporary URL before going live. + +### Deploy to a Preview Channel +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID +``` +Replace `CHANNEL_ID` with a name (e.g., `feature-beta`). +This returns a preview URL like `PROJECT_ID--CHANNEL_ID-RANDOM_HASH.web.app`. + +### Expiration +Channels expire after 7 days by default. To set a different expiration: +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID --expires 1d +``` + +## Cloning to Live +You can promote a version from a preview channel to your live channel without rebuilding. + +```bash +npx -y firebase-tools@latest hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL_ID TARGET_SITE_ID:live +``` + +**Example:** +Clone the `feature-beta` channel on your default site to live: +```bash +npx -y firebase-tools@latest hosting:clone my-project:feature-beta my-project:live +``` diff --git a/.agents/skills/firestore-security-rules-auditor/SKILL.md b/.agents/skills/firestore-security-rules-auditor/SKILL.md new file mode 100644 index 0000000..9917b06 --- /dev/null +++ b/.agents/skills/firestore-security-rules-auditor/SKILL.md @@ -0,0 +1,46 @@ +--- +name: firestore-security-rules-auditor +description: A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust. +--- + +# Overview +This skill acts as an auditor for Firebase Security Rules, evaluating them against a rigorous set of criteria to ensure they are secure, robust, and correctly implemented. + +# Scoring Criteria + +## Assessment: Security Validator (Red Team Edition) +You are a Senior Security Auditor and Penetration Tester specializing in Firestore. Your goal is to find "the hole in the wall." Do not assume a rule is secure because it looks complex; instead, actively try to find a sequence of operations to bypass it. + +### Mandatory Audit Checklist: +1. **The Update Bypass:** Compare 'create' and 'update' rules. Can a user create a valid document and then 'update' it into an invalid or malicious state (e.g., changing their role, bypassing size limits, or corrupting data types)? +2. **Authority Source:** Does the security rely on user-provided data (request.resource.data) for sensitive fields like 'role', 'isAdmin', or 'ownerId'? Carefully consider the source for that authority. +3. **Business Logic vs. Rules:** Does the rule set actually support the app's purpose? (e.g., In a collaboration app, can collaborators actually read the data? If not, the rules are "broken" or will force insecure workarounds). +4. **Storage Abuse:** Are there string length or array size limits? If not, label it as a "Resource Exhaustion/DoS" risk. +5. **Type Safety:** Are fields checked with 'is string', 'is int', or 'is timestamp'? +6. **Field-Level vs. Identity-Level Security:** Be careful with rules that use \`hasOnly()\` or \`diff()\`. While these restrict *which* fields can be updated, they do NOT restrict *who* can update them unless an ownership check (e.g., \`resource.data.uid == request.auth.uid\`) is also present. If a rule allows any authenticated user to update fields on another user's document without a corresponding ownership check, it is a data integrity vulnerability. + +### Admin Bootstrapping & Privileges: +The admin bootstrapping process is limited in this app. If the rules use a single hardcoded admin email (e.g., checking request.auth.token.email == 'admin@example.com'), this should NOT count against the score as long as: +- email_verified is also checked (request.auth.token.email_verified == true). +- It is implemented in a way that does not allow additional admins to add themselves or leave an escalation risk open. + +### Scoring Criteria (1-5): +- **1 (Critical):** Unauthorized data access (leaks), privilege escalation, or total validation bypass. +- **2 (Major):** Broken business logic, self-assigned roles, bypass of controls. +- **3 (Moderate):** PII exposure (e.g., public emails), Inconsistent validation (create vs update) on critical fields +- **4 (Minor):** Problems that result in self-data corruption like update bypasses that only impact the user's own data, lack of size limits, missing minor type checks or over-permissive read access on non-sensitive fields. +- **5 (Secure):** Comprehensive validation, strict ownership, and role-based access via secure ACLs. + +Return your assessment in JSON format using the following structure: +{ + "score": 1-5, + "summary": "overall assessment", + "findings": [ + { + "check": "checklist item", + "severity": "critical|major|moderate|minor", + "issue": "description", + "recommendation": "fix" + } + ] +} \ No newline at end of file diff --git a/.firebase/hosting.YnVpbGQvd2Vi.cache b/.firebase/hosting.YnVpbGQvd2Vi.cache new file mode 100644 index 0000000..4e17990 --- /dev/null +++ b/.firebase/hosting.YnVpbGQvd2Vi.cache @@ -0,0 +1,35 @@ +version.json,1776641270181,85b44cf9c484465a153bfcbc45e51b5bec0c6b0bbd08ddb748676f1be9148966 +manifest.json,1776641271305,5dbc40d112feda18ef93319d9dc901933db018ec87c163ee1792eeef94c6c09e +flutter_service_worker.js,1776643113637,e1f4135191a080af3d1ba569557b5277252b9b9423a6be83c963274d08d39f5f +index.html,1776643085343,e41d5c8da63bc8625a0fb6c6ed8516a6876091a299138e2f34735c479ed68847 +favicon.png,1776641271305,18f5974cf0a7a778cc393e3cb31725d0a85970c8df2b52688cacce7e4dc99342 +icons/Icon-maskable-192.png,1776641271305,3b3af8b09702ed3f063219466bd9e044dbd2703372b1402f6632920ba9c251de +flutter_bootstrap.js,1776643085338,de59f25cc72fcb37144c8fdbd5d6687f10910d9ce86150d50071a5cea7c723f0 +flutter.js,1776643085064,c86e9ec2a28b0fa50e6efcc196aec60be02c96a5b0bec888ea7e1c986d1b8c68 +icons/Icon-512.png,1776641271305,7fdb40ad7ef7200d89786b1266b41d441eea7872d4bdccaf8a954429aab62c5f +icons/Icon-192.png,1776641271305,2a485edb60e647cf0496f958c90c1ebdb3b9a82dc44260370b9094842fab3906 +assets/FontManifest.json,1776641270262,00798c3c5766cdc753371ca1934749c9fe9b8969de56bc54e9ed1c90b3d669fa +assets/AssetManifest.bin.json,1776641270262,6dab3bc22d8651a5fa292a09e03cfd63b9c06be7d92099be1e7c492a94623f6b +assets/AssetManifest.bin,1776641270262,8b6072cd7e29821eb7524c128faf9c41e69579e2a2fc8dd76b5140802f2e0de6 +assets/shaders/stretch_effect.frag,1776641270339,5936632aca690916d8c46a627c9bac73438a20ac1a3d10464c93f7fff94eabec +assets/packages/cupertino_icons/assets/CupertinoIcons.ttf,1776641271299,10aa1f084fa7612decf021fb5a8aefa4a7d2f427d7a02fa778962dd20b814c29 +assets/shaders/ink_sparkle.frag,1776641270334,5173811eeecee36d442b414b44ec54993cadd39e44568fb88a24dc7ff3dd1fca +icons/Icon-maskable-512.png,1776641271305,8d3ccbc9307d2a1ede82dddcd23c11d39a00be576296b9358903ee746206cde2 +assets/fonts/MaterialIcons-Regular.otf,1776641271303,ca87fff66393b1255b3684a3cb9148345d7815d0777dd7a75fdab9f8ddb33d72 +canvaskit/wimp.js,1776643085061,155c03184c816768553bdabac007c209b0b080d5e9c3689afc53a55e08337dcc +canvaskit/skwasm_heavy.js,1776643085036,b6844567b8a37fb14d5662b11016d44581d63cad3a8d81002ccda2df422f6b06 +canvaskit/skwasm.js,1776643085061,ca9eea4a35f28735e5db9891a9761e61362eb920e207c9e92b44bf1b219411a4 +canvaskit/canvaskit.js,1776643085061,fa4d7a33ccb6339247171eab8a5caddecbb0e5a4434ce9053f35363f2b6b189c +canvaskit/chromium/canvaskit.js,1776643085058,4d89e6a67e87c4b16ce2aeeeebc2d45679bd496a261052ee18267abad2c48a7e +assets/NOTICES,1776641270263,d95a969eb5a115802462eb514403d473d9def4cd76e6bc20a95f59bfa26d1bd2 +canvaskit/chromium/canvaskit.js.symbols,1776643085059,9e879f9e28effde984d429c56a54310544f269be49bda13be0c379de9cb71b43 +canvaskit/canvaskit.js.symbols,1776643085063,c1799ed8ced2395383e855ba33e33f51e00a545c0b0e092886edb8ac26caf4e7 +canvaskit/skwasm.js.symbols,1776643085035,91d396bb2de3a8e36c8a7aeba131dd588da90c3f3d0bc0aeb1ec27386a79ab51 +canvaskit/wimp.js.symbols,1776643085061,bfff908f573a0af5c2f9f35f6c62e2bd62b1285be0b6a2be749c9de5bf579968 +canvaskit/skwasm_heavy.js.symbols,1776643085036,a264488be276a5f5dfed794072e80fdaab6abd0d932aec0ab42046d0efa646ae +main.dart.js,1776641270179,3698c745ceb8fce3196e3eb7f8bd7e882a9cf220b36c2670cb547abb87ccbd2f +canvaskit/wimp.wasm,1776643085037,1613355926b40c90ff7aef18576a62fdb429e27c98096f3a4b8218117ccabb06 +canvaskit/skwasm.wasm,1776643085060,4aa67861d67269e617537b1795832531ddd79e95e8afed6a0cbd565ed78a960b +canvaskit/chromium/canvaskit.wasm,1776643085041,e545908d5764c6a49776fcaeecbbba2935aab38b7e288549141701cbae597d72 +canvaskit/skwasm_heavy.wasm,1776643085063,05e0bbd67d9f87e8852a85cc9c7b794564f42b2ce66930579ed4917e447c788f +canvaskit/canvaskit.wasm,1776643085039,bdf154888353ea6c1b503ce59585f72eccf24a7f197019266c94d2b0216b5d5c diff --git a/.firebaserc b/.firebaserc new file mode 100644 index 0000000..77ad204 --- /dev/null +++ b/.firebaserc @@ -0,0 +1,5 @@ +{ + "projects": { + "default": "onsol-go" + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..e4b4e8b --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: android + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: ios + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: linux + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: macos + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: web + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + - platform: windows + create_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + base_revision: 2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100644 index 0000000..16fad47 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# onsolgo + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..e8ea8c2 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,47 @@ +plugins { + id("com.android.application") + // START: FlutterFire Configuration + id("com.google.gms.google-services") + // END: FlutterFire Configuration + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.stnebula.onsolgo.onsolgo" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.stnebula.onsolgo.onsolgo" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 0000000..fa9b884 --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,29 @@ +{ + "project_info": { + "project_number": "128426171433", + "project_id": "onsol-go", + "storage_bucket": "onsol-go.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:128426171433:android:618cd582a847a9a5fe5038", + "android_client_info": { + "package_name": "com.stnebula.onsolgo.onsolgo" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyAoS2uuI3uX4XwA0oPVyX94j-HV1MeLlOw" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6db4bd1 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/stnebula/onsolgo/onsolgo/MainActivity.kt b/android/app/src/main/kotlin/com/stnebula/onsolgo/onsolgo/MainActivity.kt new file mode 100644 index 0000000..ecc3314 --- /dev/null +++ b/android/app/src/main/kotlin/com/stnebula/onsolgo/onsolgo/MainActivity.kt @@ -0,0 +1,5 @@ +package com.stnebula.onsolgo.onsolgo + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2b30ce5 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..a532153 Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..ae4d9e2 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..5c5ae79 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..69d8a41 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/launcher_icon.png b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png new file mode 100644 index 0000000..221b725 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/launcher_icon.png b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png new file mode 100644 index 0000000..f3ac39a Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png new file mode 100644 index 0000000..27cd092 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png new file mode 100644 index 0000000..33ac2e3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png new file mode 100644 index 0000000..b570722 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..beab31f --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #000000 + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..174f408 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,29 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + // START: FlutterFire Configuration + id("com.google.gms.google-services") version("4.3.15") apply false + // END: FlutterFire Configuration + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/assets/icon/app_icon.png b/assets/icon/app_icon.png new file mode 100644 index 0000000..f683e1c Binary files /dev/null and b/assets/icon/app_icon.png differ diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..ce92303 --- /dev/null +++ b/firebase.json @@ -0,0 +1,45 @@ +{ + "firestore": { + "rules": "firestore.rules" + }, + "storage": { + "rules": "storage.rules" + }, + "flutter": { + "platforms": { + "android": { + "default": { + "projectId": "onsol-go", + "appId": "1:128426171433:android:618cd582a847a9a5fe5038", + "fileOutput": "android/app/google-services.json" + } + }, + "dart": { + "lib/firebase_options.dart": { + "projectId": "onsol-go", + "configurations": { + "android": "1:128426171433:android:618cd582a847a9a5fe5038", + "ios": "1:128426171433:ios:c9499633c66d705ffe5038", + "macos": "1:128426171433:ios:c9499633c66d705ffe5038", + "web": "1:128426171433:web:5b27ec0fdfceee78fe5038", + "windows": "1:128426171433:web:efaf8cf4fb14cd7ffe5038" + } + } + } + } + }, + "hosting": { + "public": "build/web", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ] + } +} diff --git a/firestore.rules b/firestore.rules new file mode 100644 index 0000000..32619ac --- /dev/null +++ b/firestore.rules @@ -0,0 +1,157 @@ +rules_version = '2'; + +service cloud.firestore { + match /databases/{database}/documents { + + // --- HELPERS --- + function isSignedIn() { + return request.auth != null; + } + + function isAdmin() { + return isSignedIn() + && exists(/databases/$(database)/documents/users/$(request.auth.uid)) + && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin'; + } + + // Toggle like on social_posts: only likedBy + likes may change; count must match list length. + function isSocialLikeReactionUpdate() { + return isSignedIn() + && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['likedBy', 'likes']) + && request.resource.data.likedBy is list + && request.resource.data.likes == request.resource.data.likedBy.size(); + } + + // --- USERS --- + match /users/{userId} { + allow get: if true; + allow list: if isAdmin(); + + allow create: if isSignedIn() && request.auth.uid == userId; + + allow update: if isAdmin() || ( + isSignedIn() + && request.auth.uid == userId + && !request.resource.data.diff(resource.data).affectedKeys() + .hasAny(['rankLevel', 'role', 'isVerified', 'isBanned']) + ); + + match /{allPaths=**} { + allow read, write: if isSignedIn() && (request.auth.uid == userId || isAdmin()); + } + } + + // --- SOCIAL --- + match /social_posts/{postId} { + allow read: if true; + + allow create: if isSignedIn() + && request.resource.data.authorId == request.auth.uid; + + allow update: if isAdmin() || ( + isSignedIn() + && resource.data.authorId == request.auth.uid + && request.resource.data.authorId == resource.data.authorId + ) || isSocialLikeReactionUpdate(); + + allow delete: if isAdmin() + || (isSignedIn() && resource.data.authorId == request.auth.uid); + + match /comments/{commentId} { + allow read: if true; + allow create: if isSignedIn() + && request.resource.data.uid == request.auth.uid; + allow update, delete: if isAdmin() + || (isSignedIn() && resource.data.uid == request.auth.uid); + } + } + + // --- UPCOMING (Soon tab; artists manage own rows) --- + match /upcoming/{announcementId} { + allow read: if true; + + allow create: if isSignedIn() + && request.resource.data.authorId == request.auth.uid + && request.resource.data.keys().hasAll([ + 'kind', 'authorId', 'authorName', 'seriesTitle' + ]) + && request.resource.data.kind in ['new_series', 'chapter_drop'] + && ( + request.resource.data.dateTbd == true + || request.resource.data.targetDate is timestamp + ); + + allow update: if isAdmin() || ( + isSignedIn() + && resource.data.authorId == request.auth.uid + && request.resource.data.authorId == resource.data.authorId + ); + + allow delete: if isAdmin() + || (isSignedIn() && resource.data.authorId == request.auth.uid); + } + + // --- MANGA & CHAPTERS --- + match /manga/{mangaId} { + allow read: if true; + + // Anyone signed in can bump read counts; series author can edit portfolio fields. + allow update: if isAdmin() + || (isSignedIn() + && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['reads'])) + || (isSignedIn() + && resource.data.keys().hasAll(['authorId']) + && resource.data.authorId == request.auth.uid + && request.resource.data.authorId == resource.data.authorId + && request.resource.data.diff(resource.data).affectedKeys() + .hasOnly(['coverUrl', 'bannerUrl', 'synopsis', 'aboutArtist', 'socials'])); + + allow write: if isAdmin(); + + match /chapters/{chapterId} { + allow read: if true; + + allow create, update: if isAdmin(); + + allow delete: if isAdmin() + || (isSignedIn() + && exists(/databases/$(database)/documents/manga/$(mangaId)) + && get(/databases/$(database)/documents/manga/$(mangaId)).data.authorId == request.auth.uid); + + match /page_interactions/{pageId} { + allow read: if true; + allow create, update: if isSignedIn(); + + match /comments/{commentId} { + allow read: if true; + allow create: if isSignedIn() + && request.resource.data.uid == request.auth.uid; + allow update: if isAdmin() + || (isSignedIn() && resource.data.uid == request.auth.uid); + allow delete: if isAdmin() + || (isSignedIn() && resource.data.uid == request.auth.uid); + } + } + } + } + + // --- MARKETPLACE --- + match /marketplace/{itemId} { + allow read: if true; + allow write: if isAdmin(); + } + + // Sign-up validates a known code via get(); listing all codes is admin-only. + match /invite_codes/{code} { + allow get: if true; + allow list: if isAdmin(); + allow create, update, delete: if isAdmin(); + } + + // --- SYSTEM BROADCAST --- + match /system/announcement { + allow read: if true; + allow write: if isAdmin(); + } + } +} diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..288401f --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..ea93f60 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..9745213 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..08c9f15 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..3557b75 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..86a97dd Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..2e9c2d2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..db259ee Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..08c9f15 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..40e2b17 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..069e680 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..6f63445 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..be0e43b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..1318d86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..c144d24 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..069e680 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..72b8a8e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..221b725 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..33ac2e3 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..e1e7620 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..d36aa3e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..9a6ca38 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..06b8bee --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Onsolgo + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + onsolgo + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/core/achievement_manager.dart b/lib/core/achievement_manager.dart new file mode 100644 index 0000000..02f4507 --- /dev/null +++ b/lib/core/achievement_manager.dart @@ -0,0 +1,34 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/constants.dart'; + +class AchievementManager { + static Future unlock(String uid, String achId) async { + final ref = FirebaseFirestore.instance.collection('users').doc(uid).collection('achievements').doc(achId); + final doc = await ref.get(); + if (!doc.exists) { + await ref.set({'unlockedAt': FieldValue.serverTimestamp()}); + } + } + + static Future incrementStat(String uid, String field, {int amount = 1}) async { + final userRef = FirebaseFirestore.instance.collection('users').doc(uid); + await userRef.update({field: FieldValue.increment(amount)}); + + final snap = await userRef.get(); + final d = snap.data() as Map; + + // Threshold Checks + if (field == 'pagesRead') { + int p = safeInt(d['pagesRead']); + if (p >= 10) unlock(uid, "page_turner_1"); + if (p >= 50) unlock(uid, "page_turner_2"); + if (p >= 200) unlock(uid, "page_turner_3"); + } + if (field == 'chaptersRead') { + int c = safeInt(d['chaptersRead']); + if (c >= 1) unlock(uid, "chapter_complete_1"); + if (c >= 10) unlock(uid, "chapter_complete_2"); + if (c >= 50) unlock(uid, "chapter_complete_3"); + } + } +} \ No newline at end of file diff --git a/lib/core/ad_handler.dart b/lib/core/ad_handler.dart new file mode 100644 index 0000000..bc674a5 --- /dev/null +++ b/lib/core/ad_handler.dart @@ -0,0 +1,42 @@ +import 'package:google_mobile_ads/google_mobile_ads.dart'; +import 'package:flutter/foundation.dart'; +import 'package:onsolgo/core/constants.dart'; + +class AdHandler { + static InterstitialAd? _interstitialAd; + + static void loadInterstitialAd() { + if (kIsWeb) return; // Skip on PWA + + InterstitialAd.load( + adUnitId: kInterstitialAdUnitId, + request: const AdRequest(), + adLoadCallback: InterstitialAdLoadCallback( + onAdLoaded: (ad) => _interstitialAd = ad, + onAdFailedToLoad: (error) => _interstitialAd = null, + ), + ); + } + + static void showInterstitialAd(Function onAdClosed) { + if (kIsWeb || _interstitialAd == null) { + onAdClosed(); // If web or ad not ready, just open the chapter + return; + } + + _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback( + onAdDismissedFullScreenContent: (ad) { + ad.dispose(); + loadInterstitialAd(); // Load next one + onAdClosed(); // Open the chapter + }, + onAdFailedToShowFullScreenContent: (ad, error) { + ad.dispose(); + onAdClosed(); + }, + ); + + _interstitialAd!.show(); + _interstitialAd = null; + } +} \ No newline at end of file diff --git a/lib/core/constants.dart b/lib/core/constants.dart new file mode 100644 index 0000000..4f9ffb7 --- /dev/null +++ b/lib/core/constants.dart @@ -0,0 +1,165 @@ +import 'package:flutter/material.dart'; + +// --- BRANDING --- +const String kOnsolBanner = "https://files.onsolgo.cloud/manaa/assets/onsol-banner.png"; +const String kOnsolAppWebUrl = 'https://onsol-go.web.app'; +const Color kOnsolGold = Color(0xFFFFD700); + +/// Share targets for web (query params; app may resolve these later). +String kOnsolSharePostUrl(String postId) => '$kOnsolAppWebUrl?post=$postId'; + +String kOnsolShareChapterUrl(String mangaId, Object? chapterNumber) => + '$kOnsolAppWebUrl?manga=$mangaId&ch=$chapterNumber'; + +// --- THE 5-TIER RANK LOGIC --- +String getRankName(int level) { + switch (level) { + case 1: return "READER"; + case 2: return "BACKER"; + case 3: return "INVESTOR"; + case 4: return "STEWARD"; + case 5: return "VERIFIED ManaA ARTIST"; + default: return "READER"; + } +} + +Color getRankColor(int level) { + switch (level) { + case 1: return Colors.grey; + case 2: return Colors.orangeAccent; + case 3: return Colors.cyanAccent; + case 4: return Colors.amber; + case 5: return kOnsolGold; + default: return Colors.grey; + } +} + +IconData getRankIcon(int level) { + switch (level) { + case 1: return Icons.person; + case 2: return Icons.bolt; + case 3: return Icons.token; + case 4: return Icons.shield; + case 5: return Icons.verified; + default: return Icons.person; + } +} + +Widget verifiedBadge(bool isVerified, {double size = 16}) { + if (!isVerified) return const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.only(left: 6), + child: Icon(Icons.verified, color: kOnsolGold, size: size), + ); +} + +int safeInt(dynamic value) { + if (value == null) return 0; + if (value is int) return value; + if (value is double) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; +} + +// --- MASTER ACHIEVEMENT MODEL --- +class AchievementModel { + final String id, title, desc, category; + final IconData icon; + const AchievementModel({ + required this.id, + required this.title, + required this.desc, + required this.category, + required this.icon + }); +} + +// --- ADMOB CONFIGURATION --- + +// 1. THIS GOES IN YOUR ANDROID MANIFEST (Real App ID from AdMob) +const String kAdMobAppId = "ca-app-pub-7461835411004007~7412162757"; + +// 2. THE AD UNIT IDS +// For now, these are GOOGLE TEST IDs so you don't get banned. +// Replace these with your REAL IDs only when you upload to the Play Store. + +// Unit: Interstitial (Full Screen) +const String kInterstitialAdUnitId = "ca-app-pub-3940256099942544/1033173712"; + +// Unit: Banner (Small strip) +const String kBannerAdUnitId = "ca-app-pub-3940256099942544/6300978111"; + +// --- FULL ACHIEVEMENT LIST (FROM PHOTOS) --- +const List kAllAchievements = [ + // ACCOUNT & ONBOARDING + AchievementModel(id: "initiate", title: "INITIATE", desc: "Account created", category: "ACCOUNT", icon: Icons.flag), + AchievementModel(id: "profile_activated", title: "PROFILE ACTIVATED", desc: "Profile completed (bio + avatar)", category: "ACCOUNT", icon: Icons.face), + AchievementModel(id: "first_login", title: "FIRST LOGIN", desc: "First successful login session", category: "ACCOUNT", icon: Icons.login), + AchievementModel(id: "return_user", title: "RETURN USER", desc: "Logged in on 2 separate days", category: "ACCOUNT", icon: Icons.replay), + AchievementModel(id: "verified_access", title: "VERIFIED ACCESS", desc: "Email or phone verified", category: "ACCOUNT", icon: Icons.verified_user), + + // READING PROGRESSION + AchievementModel(id: "first_contact", title: "FIRST CONTACT", desc: "Open first chapter", category: "READING", icon: Icons.play_arrow), + AchievementModel(id: "page_turner_1", title: "PAGE TURNER I", desc: "Read 10 pages", category: "READING", icon: Icons.auto_stories), + AchievementModel(id: "page_turner_2", title: "PAGE TURNER II", desc: "Read 50 pages", category: "READING", icon: Icons.menu_book), + AchievementModel(id: "page_turner_3", title: "PAGE TURNER III", desc: "Read 200 pages", category: "READING", icon: Icons.library_books), + AchievementModel(id: "chapter_complete_1", title: "CHAPTER COMPLETE I", desc: "Finish 1 chapter", category: "READING", icon: Icons.task_alt), + AchievementModel(id: "chapter_complete_2", title: "CHAPTER COMPLETE II", desc: "Finish 10 chapters", category: "READING", icon: Icons.done_all), + AchievementModel(id: "chapter_complete_3", title: "CHAPTER COMPLETE III", desc: "Finish 50 chapters", category: "READING", icon: Icons.checklist_rtl), + AchievementModel(id: "volume_devourer", title: "VOLUME DEVOURER", desc: "Finish a full volume", category: "READING", icon: Icons.auto_awesome_motion), + AchievementModel(id: "binge_reader", title: "BINGE READER", desc: "Read 3 chapters in one session", category: "READING", icon: Icons.flash_on), + AchievementModel(id: "locked_in", title: "LOCKED IN", desc: "Read 5 chapters in one session", category: "READING", icon: Icons.lock), + + // COMMUNITY & ENGAGEMENT + AchievementModel(id: "voice_activated", title: "VOICE ACTIVATED", desc: "First comment posted", category: "COMMUNITY", icon: Icons.comment), + AchievementModel(id: "panel_reactor", title: "PANEL REACTOR", desc: "React to a panel", category: "COMMUNITY", icon: Icons.add_reaction), + AchievementModel(id: "conversation_starter", title: "CONV. STARTER", desc: "Start a thread", category: "COMMUNITY", icon: Icons.forum), + AchievementModel(id: "community_member", title: "COMMUNITY MEMBER", desc: "5 comments posted", category: "COMMUNITY", icon: Icons.groups), + AchievementModel(id: "recognized_voice", title: "RECOGNIZED VOICE", desc: "10 likes on a comment", category: "COMMUNITY", icon: Icons.campaign), + AchievementModel(id: "fan_favorite", title: "FAN FAVORITE", desc: "50 likes on a comment", category: "COMMUNITY", icon: Icons.favorite), + AchievementModel(id: "creator_noticed", title: "CREATOR NOTICED", desc: "Creator replies to you", category: "COMMUNITY", icon: Icons.star), + AchievementModel(id: "debate_ready", title: "DEBATE READY", desc: "Participate in 5 discussions", category: "COMMUNITY", icon: Icons.psychology), + + // MARKETPLACE & COLLECTION + AchievementModel(id: "first_acquisition", title: "FIRST ACQUISITION", desc: "First purchase", category: "MARKET", icon: Icons.shopping_bag), + AchievementModel(id: "collector_1", title: "COLLECTOR I", desc: "Own 3 items", category: "MARKET", icon: Icons.layers), + AchievementModel(id: "collector_2", title: "COLLECTOR II", desc: "Own 10 items", category: "MARKET", icon: Icons.inventory_2), + AchievementModel(id: "archivist", title: "ARCHIVIST", desc: "Own a full volume", category: "MARKET", icon: Icons.folder_special), + AchievementModel(id: "limited_hunter", title: "LIMITED HUNTER", desc: "Purchase a limited drop", category: "MARKET", icon: Icons.timer), + AchievementModel(id: "artifact_holder", title: "ARTIFACT HOLDER", desc: "Purchase premium tier item", category: "MARKET", icon: Icons.token), + AchievementModel(id: "vault_builder", title: "VAULT BUILDER", desc: "Own items from 3 creators", category: "MARKET", icon: Icons.account_balance), + + // SUPPORT & INVESTMENT + AchievementModel(id: "first_backer", title: "FIRST BACKER", desc: "First financial support", category: "INVEST", icon: Icons.volunteer_activism), + AchievementModel(id: "supporter", title: "SUPPORTER", desc: "Subscribe to a creator", category: "INVEST", icon: Icons.card_membership), + AchievementModel(id: "series_builder", title: "SERIES BUILDER", desc: "Support 3 creators", category: "INVEST", icon: Icons.build), + AchievementModel(id: "investor_1", title: "INVESTOR I", desc: "Spend \$25 total", category: "INVEST", icon: Icons.monetization_on), + AchievementModel(id: "investor_2", title: "INVESTOR II", desc: "Spend \$100 total", category: "INVEST", icon: Icons.payments), + AchievementModel(id: "investor_3", title: "INVESTOR III", desc: "Spend \$250 total", category: "INVEST", icon: Icons.account_balance_wallet), + AchievementModel(id: "day_one", title: "DAY ONE BACKER", desc: "Support series before Chapter 3", category: "INVEST", icon: Icons.first_page), + AchievementModel(id: "loyal_patron", title: "LOYAL PATRON", desc: "Maintain subscription for 3 months", category: "INVEST", icon: Icons.loyalty), + + // CONSISTENCY + AchievementModel(id: "back_tomorrow", title: "BACK TOMORROW", desc: "2-day streak", category: "CONSISTENCY", icon: Icons.history), + AchievementModel(id: "discipline", title: "3-DAY DISCIPLINE", desc: "3-day streak", category: "CONSISTENCY", icon: Icons.self_improvement), + AchievementModel(id: "weekly_ritual", title: "WEEKLY RITUAL", desc: "7-day streak", category: "CONSISTENCY", icon: Icons.calendar_month), + AchievementModel(id: "monthly_reader", title: "MONTHLY READER", desc: "30-day streak", category: "CONSISTENCY", icon: Icons.calendar_today), + AchievementModel(id: "no_days_off", title: "NO DAYS OFF", desc: "60-day streak", category: "CONSISTENCY", icon: Icons.hotel_class), + + // DISCOVERY + AchievementModel(id: "explorer_1", title: "EXPLORER I", desc: "Read 3 different series", category: "DISCOVERY", icon: Icons.explore), + AchievementModel(id: "explorer_2", title: "EXPLORER II", desc: "Read 5 different series", category: "DISCOVERY", icon: Icons.explore_off), + AchievementModel(id: "explorer_3", title: "EXPLORER III", desc: "Read 10 different series", category: "DISCOVERY", icon: Icons.public), + AchievementModel(id: "genre_breaker", title: "GENRE BREAKER", desc: "Read outside your usual category", category: "DISCOVERY", icon: Icons.extension), + AchievementModel(id: "new_blood", title: "NEW BLOOD", desc: "Read a newly released series", category: "DISCOVERY", icon: Icons.fiber_new), + AchievementModel(id: "early_witness", title: "EARLY WITNESS", desc: "Read within 24 hours of drop", category: "DISCOVERY", icon: Icons.access_time), + + // RARE / HIDDEN + AchievementModel(id: "night_reader", title: "NIGHT READER", desc: "Read between 2AM-5AM", category: "RARE", icon: Icons.dark_mode), + AchievementModel(id: "marathon", title: "MARATHON", desc: "2+ hours in one session", category: "RARE", icon: Icons.timer), + AchievementModel(id: "silent_watcher", title: "SILENT WATCHER", desc: "Read 20 chapters with no comments", category: "RARE", icon: Icons.visibility_off), + AchievementModel(id: "break_loop", title: "BREAK THE LOOP", desc: "Return after 30 days inactive", category: "RARE", icon: Icons.loop), + AchievementModel(id: "og_member", title: "OG MEMBER", desc: "Joined during beta", category: "RARE", icon: Icons.auto_awesome), + AchievementModel(id: "founder_circle", title: "FOUNDER'S CIRCLE", desc: "Invited directly", category: "RARE", icon: Icons.stars), + AchievementModel(id: "system_maxed", title: "SYSTEM MAXED", desc: "Complete all reading achievements", category: "RARE", icon: Icons.diamond), +]; \ No newline at end of file diff --git a/lib/core/energy_manager.dart b/lib/core/energy_manager.dart new file mode 100644 index 0000000..ad7dac9 --- /dev/null +++ b/lib/core/energy_manager.dart @@ -0,0 +1,31 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; + +class VigorManager { + static const int maxVigor = 3; + static const int rechargeHours = 3; + + static Future getAvailableVigor(Map userData) async { + int currentVigor = userData['vigor'] ?? maxVigor; + Timestamp? lastVigorRefill = userData['lastVigorRefill']; + + if (lastVigorRefill == null) return currentVigor; + + // Calculate time since last refill + DateTime lastTime = lastVigorRefill.toDate(); + Duration diff = DateTime.now().difference(lastTime); + + // If more than 3 hours have passed, full refill + if (diff.inHours >= rechargeHours) { + return maxVigor; + } + + return currentVigor; + } + + static Future consumeVigor(String uid, int currentVigor) async { + await FirebaseFirestore.instance.collection('users').doc(uid).update({ + 'vigor': currentVigor - 1, + 'lastVigorRefill': FieldValue.serverTimestamp(), + }); + } +} \ No newline at end of file diff --git a/lib/core/share_helper.dart b/lib/core/share_helper.dart new file mode 100644 index 0000000..4108fcb --- /dev/null +++ b/lib/core/share_helper.dart @@ -0,0 +1,104 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:share_plus/share_plus.dart'; +import 'package:onsolgo/core/constants.dart'; + +/// Captures a [RepaintBoundary] (via [key]) as PNG and shares it with [text] and a [link] +/// (defaults to [kOnsolAppWebUrl]). Uses in-memory bytes only (no [dart:io]). +class OnsolShare { + static Future share(GlobalKey key, String text, {String? link}) => + _shareImpl(key, text, link: link); +} + +Future _shareImpl(GlobalKey key, String text, {String? link}) async { + final url = (link ?? kOnsolAppWebUrl).trim(); + String bodyWithLink(String raw) { + final caption = raw.trim().isEmpty ? 'ONSOL-GO!' : raw.trim(); + if (caption.contains(url)) return caption; + return '$caption\n\n$url'; + } + + final fallbackMessage = bodyWithLink(text); + + Future shareText(String value) async { + await SharePlus.instance.share(ShareParams(text: value)); + } + + Future clipboard(String value) async { + await Clipboard.setData(ClipboardData(text: value)); + } + + try { + final ctx = key.currentContext; + if (ctx == null || !ctx.mounted) { + await shareText(fallbackMessage); + return; + } + + await SchedulerBinding.instance.endOfFrame; + + if (!ctx.mounted) { + await shareText(fallbackMessage); + return; + } + + final boundary = ctx.findRenderObject(); + if (boundary is! RenderRepaintBoundary) { + await shareText(fallbackMessage); + return; + } + + final image = await boundary.toImage(pixelRatio: 3.0); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + if (byteData == null) { + await shareText(fallbackMessage); + return; + } + + final pngBytes = byteData.buffer.asUint8List(); + final file = XFile.fromData( + pngBytes, + mimeType: 'image/png', + name: 'onsol_share.png', + ); + + try { + await SharePlus.instance.share( + ShareParams(files: [file], text: bodyWithLink(text)), + ); + } catch (e) { + if (kDebugMode) { + debugPrint('OnsolShare: file+caption share failed ($e), retrying file only'); + } + try { + await SharePlus.instance.share( + ShareParams(files: [file], text: bodyWithLink(text)), + ); + } catch (e2) { + if (kDebugMode) { + debugPrint('OnsolShare: file-only share failed ($e2), falling back to text'); + } + await shareText(fallbackMessage); + } + } + } catch (e, st) { + if (kDebugMode) { + debugPrint('OnsolShare error: $e\n$st'); + } + try { + await shareText(fallbackMessage); + } catch (e3) { + if (kDebugMode) { + debugPrint('OnsolShare text share failed: $e3'); + } + try { + await clipboard(fallbackMessage); + } catch (_) {} + } + } +} diff --git a/lib/core/streak_manager.dart b/lib/core/streak_manager.dart new file mode 100644 index 0000000..2832dce --- /dev/null +++ b/lib/core/streak_manager.dart @@ -0,0 +1,34 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/achievement_manager.dart'; + +class StreakManager { + static Future updateStreak(String uid) async { + final docRef = FirebaseFirestore.instance.collection('users').doc(uid); + final snap = await docRef.get(); + if (!snap.exists) return; + + final data = snap.data() as Map; + final lastVisit = (data['lastVisit'] as Timestamp?)?.toDate(); + int currentStreak = data['streak'] ?? 0; + final today = DateTime.now(); + + if (lastVisit != null) { + final diff = DateTime(today.year, today.month, today.day).difference(DateTime(lastVisit.year, lastVisit.month, lastVisit.day)).inDays; + if (diff == 1) { + currentStreak++; + await docRef.update({'streak': currentStreak, 'lastVisit': FieldValue.serverTimestamp()}); + // Streak Unlocks + if (currentStreak >= 2) AchievementManager.unlock(uid, "back_tomorrow"); + if (currentStreak >= 3) AchievementManager.unlock(uid, "3_day_discipline"); + if (currentStreak >= 7) AchievementManager.unlock(uid, "weekly_ritual"); + if (currentStreak >= 30) AchievementManager.unlock(uid, "monthly_reader"); + if (currentStreak >= 60) AchievementManager.unlock(uid, "no_days_off"); + } else if (diff > 1) { + await docRef.update({'streak': 1, 'lastVisit': FieldValue.serverTimestamp()}); + } + } else { + await docRef.update({'streak': 1, 'lastVisit': FieldValue.serverTimestamp()}); + AchievementManager.unlock(uid, "first_login"); + } + } +} \ No newline at end of file diff --git a/lib/firebase_options.dart b/lib/firebase_options.dart new file mode 100644 index 0000000..c7efcfb --- /dev/null +++ b/lib/firebase_options.dart @@ -0,0 +1,89 @@ +// File generated by FlutterFire CLI. +// ignore_for_file: type=lint +import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, kIsWeb, TargetPlatform; + +/// Default [FirebaseOptions] for use with your Firebase apps. +/// +/// Example: +/// ```dart +/// import 'firebase_options.dart'; +/// // ... +/// await Firebase.initializeApp( +/// options: DefaultFirebaseOptions.currentPlatform, +/// ); +/// ``` +class DefaultFirebaseOptions { + static FirebaseOptions get currentPlatform { + if (kIsWeb) { + return web; + } + switch (defaultTargetPlatform) { + case TargetPlatform.android: + return android; + case TargetPlatform.iOS: + return ios; + case TargetPlatform.macOS: + return macos; + case TargetPlatform.windows: + return windows; + case TargetPlatform.linux: + throw UnsupportedError( + 'DefaultFirebaseOptions have not been configured for linux - ' + 'you can reconfigure this by running the FlutterFire CLI again.', + ); + default: + throw UnsupportedError( + 'DefaultFirebaseOptions are not supported for this platform.', + ); + } + } + + static const FirebaseOptions web = FirebaseOptions( + apiKey: 'AIzaSyDmli9KyCL26sofvC8OFiyLVnXA49RDNp4', + appId: '1:128426171433:web:5b27ec0fdfceee78fe5038', + messagingSenderId: '128426171433', + projectId: 'onsol-go', + authDomain: 'onsol-go.firebaseapp.com', + storageBucket: 'onsol-go.firebasestorage.app', + measurementId: 'G-36GJY6P96Y', + ); + + static const FirebaseOptions android = FirebaseOptions( + apiKey: 'AIzaSyAoS2uuI3uX4XwA0oPVyX94j-HV1MeLlOw', + appId: '1:128426171433:android:618cd582a847a9a5fe5038', + messagingSenderId: '128426171433', + projectId: 'onsol-go', + storageBucket: 'onsol-go.firebasestorage.app', + ); + + static const FirebaseOptions ios = FirebaseOptions( + apiKey: 'AIzaSyCwMHcvC54_YDFKjhuSWHeZ4kGRpfwok_o', + appId: '1:128426171433:ios:c9499633c66d705ffe5038', + messagingSenderId: '128426171433', + projectId: 'onsol-go', + storageBucket: 'onsol-go.firebasestorage.app', + iosBundleId: 'com.stnebula.onsolgo.onsolgo', + ); + + static const FirebaseOptions macos = FirebaseOptions( + apiKey: 'AIzaSyCwMHcvC54_YDFKjhuSWHeZ4kGRpfwok_o', + appId: '1:128426171433:ios:c9499633c66d705ffe5038', + messagingSenderId: '128426171433', + projectId: 'onsol-go', + storageBucket: 'onsol-go.firebasestorage.app', + iosBundleId: 'com.stnebula.onsolgo.onsolgo', + ); + + static const FirebaseOptions windows = FirebaseOptions( + apiKey: 'AIzaSyDmli9KyCL26sofvC8OFiyLVnXA49RDNp4', + appId: '1:128426171433:web:efaf8cf4fb14cd7ffe5038', + messagingSenderId: '128426171433', + projectId: 'onsol-go', + authDomain: 'onsol-go.firebaseapp.com', + storageBucket: 'onsol-go.firebasestorage.app', + measurementId: 'G-CT9672C0JV', + ); + +} \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..de0b60d --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:google_mobile_ads/google_mobile_ads.dart'; +import 'package:onsolgo/navigation_hub.dart'; +import 'package:onsolgo/screens/auth/login_screen.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'firebase_options.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + if (!kIsWeb) { + // 1. INITIALIZE AD ENGINE + MobileAds.instance.initialize(); + + // 2. CONFIGURE TEST DEVICE (Mandatory for Pixel 10 Pro) + // This ID comes directly from your console logs + RequestConfiguration configuration = RequestConfiguration( + testDeviceIds: ["949E2F2F6403B732392FF2648C5D9B85"]); + MobileAds.instance.updateRequestConfiguration(configuration); + } + + PaintingBinding.instance.imageCache.maximumSizeBytes = 300 * 1024 * 1024; + await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); + + FirebaseFirestore.instance.settings = const Settings(persistenceEnabled: true); + + runApp(const OnsolGoApp()); +} + +class OnsolGoApp extends StatelessWidget { + const OnsolGoApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'ONSOL-GO!', + theme: ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + scaffoldBackgroundColor: Colors.black, + canvasColor: Colors.black, + colorScheme: ColorScheme.fromSeed( + seedColor: kOnsolGold, + brightness: Brightness.dark, + surface: Colors.black, + surfaceTint: Colors.transparent, + ), + appBarTheme: const AppBarTheme(backgroundColor: Colors.black, surfaceTintColor: Colors.transparent, elevation: 0), + cardTheme: const CardThemeData(color: Colors.black, surfaceTintColor: Colors.transparent), + ), + home: StreamBuilder( + stream: FirebaseAuth.instance.authStateChanges(), + builder: (context, authSnapshot) { + if (authSnapshot.hasData) { + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(authSnapshot.data!.uid).snapshots(), + builder: (context, userSnapshot) { + if (!userSnapshot.hasData) return const Scaffold(body: Center(child: CircularProgressIndicator(color: kOnsolGold))); + if (!userSnapshot.data!.exists) return const NavigationHub(); + var userData = userSnapshot.data!.data() as Map; + if (userData['isBanned'] == true) { + return const Scaffold( + body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.gavel, color: Colors.red, size: 80), + Text("EXILED", style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold, fontSize: 32, letterSpacing: 10)), + Text("REMOVED FROM THE ORDER", style: TextStyle(color: Colors.white54, fontSize: 10)), + ])), + ); + } + return const NavigationHub(); + }, + ); + } + return const LoginScreen(); + }, + ), + ); + } +} \ No newline at end of file diff --git a/lib/navigation_hub.dart b/lib/navigation_hub.dart new file mode 100644 index 0000000..1ea2515 --- /dev/null +++ b/lib/navigation_hub.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/core/streak_manager.dart'; +import 'package:onsolgo/screens/library/library_grid.dart'; +import 'package:onsolgo/screens/library/trending_list.dart'; +import 'package:onsolgo/screens/library/coming_soon.dart'; +import 'package:onsolgo/screens/market/market_hub.dart'; +import 'package:onsolgo/screens/social/social_feed.dart'; +import 'package:onsolgo/screens/profile/profile_view.dart'; + +class NavigationHub extends StatefulWidget { + const NavigationHub({super.key}); + @override + State createState() => _NavigationHubState(); +} + +class _NavigationHubState extends State { + int _currentIndex = 0; + + // REMOVED 'const' from the list to avoid the Constant Expression error + final List _tabs = [ + const LibraryGrid(), + const TrendingList(), + const ComingSoon(), + const MarketHub(), + const SocialFeed(), // Ensure this only exists in social_feed.dart + ]; + + @override + void initState() { + super.initState(); + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + if (uid.isNotEmpty) StreakManager.updateStreak(uid); + } + + @override + Widget build(BuildContext context) { + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + + return Scaffold( + backgroundColor: Colors.black, + body: Stack( + children: [ + IndexedStack(index: _currentIndex, children: _tabs), + Positioned( + top: MediaQuery.of(context).padding.top + 10, + right: 20, + child: SizedBox( + width: 45, height: 45, + child: StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(), + builder: (context, snapshot) { + int rank = 1; String? pfp; + if (snapshot.hasData && snapshot.data!.exists) { + var data = snapshot.data!.data() as Map; + rank = safeInt(data['rankLevel']); + pfp = data.containsKey('pfpUrl') ? data['pfpUrl'] : null; + } + return IconButton( + padding: EdgeInsets.zero, + // REMOVED 'const' here to fix the build error + onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => ProfileView())), + icon: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: getRankColor(rank), width: 1.5), + boxShadow: [BoxShadow(color: getRankColor(rank).withValues(alpha: 0.3), blurRadius: 10)], + ), + child: CircleAvatar( + radius: 18, + backgroundColor: Colors.black, + child: (pfp != null && pfp.isNotEmpty) + ? ClipOval( + child: CachedNetworkImage( + imageUrl: pfp, + width: 36, + height: 36, + fit: BoxFit.cover, + errorWidget: (context, url, error) => const Icon(Icons.person, size: 20, color: Colors.white), + ), + ) + : const Icon(Icons.person, size: 20, color: Colors.white), + ), + ), + ); + }, + ), + ), + ), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _currentIndex, + onTap: (index) => setState(() => _currentIndex = index), + type: BottomNavigationBarType.fixed, + backgroundColor: Colors.black, + selectedItemColor: kOnsolGold, + unselectedItemColor: Colors.grey, + selectedFontSize: 10, + unselectedFontSize: 10, + items: const [ + BottomNavigationBarItem(icon: Icon(Icons.grid_view_rounded), label: 'Library'), + BottomNavigationBarItem(icon: Icon(Icons.local_fire_department), label: 'Hot'), + BottomNavigationBarItem(icon: Icon(Icons.auto_awesome), label: 'Upcoming'), + BottomNavigationBarItem(icon: Icon(Icons.token), label: 'Vault'), + BottomNavigationBarItem(icon: Icon(Icons.forum_rounded), label: 'Social'), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/admin/admin_dashboard.dart b/lib/screens/admin/admin_dashboard.dart new file mode 100644 index 0000000..4a483ba --- /dev/null +++ b/lib/screens/admin/admin_dashboard.dart @@ -0,0 +1,259 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'dart:math'; + +class AdminDashboard extends StatelessWidget { + const AdminDashboard({super.key}); + + // --- LOGIC: SYSTEM BROADCAST --- + void _editAnnouncement(BuildContext context) async { + final tC = TextEditingController(); + final mC = TextEditingController(); + bool active = true; + + try { + var existing = await FirebaseFirestore.instance.collection('system').doc('announcement').get(); + if (existing.exists) { + final map = existing.data(); + if (map != null) { + tC.text = map['title']?.toString() ?? ''; + mC.text = map['message']?.toString() ?? ''; + active = map['isActive'] as bool? ?? true; + } + } + } catch (e) { + debugPrint("Load Error: $e"); + } + + if (!context.mounted) return; + showDialog( + context: context, + builder: (ctx) => StatefulBuilder( + builder: (ctx, setS) => AlertDialog( + backgroundColor: Colors.grey[900], + title: const Text("SYSTEM BROADCAST", style: TextStyle(color: kOnsolGold, fontSize: 14, fontWeight: FontWeight.bold)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField(controller: tC, decoration: const InputDecoration(hintText: "Headline")), + const SizedBox(height: 10), + TextField(controller: mC, maxLines: 3, decoration: const InputDecoration(hintText: "Message")), + SwitchListTile( + title: const Text("Show Popup", style: TextStyle(fontSize: 12)), + value: active, + activeThumbColor: kOnsolGold, + onChanged: (v) => setS(() => active = v) + ), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("CANCEL", style: TextStyle(color: Colors.grey))), + ElevatedButton( + onPressed: () async { + await FirebaseFirestore.instance.collection('system').doc('announcement').set({ + 'title': tC.text.trim(), + 'message': mC.text.trim(), + 'isActive': active, + 'updatedAt': FieldValue.serverTimestamp() + }); + if (context.mounted) Navigator.pop(ctx); + }, + child: const Text("TRANSMIT"), + ) + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 4, + child: Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.red[900], + title: const Text("COMMAND CENTER", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + actions: [ + IconButton(icon: const Icon(Icons.podcasts), onPressed: () => _editAnnouncement(context)) + ], + bottom: const TabBar( + labelStyle: TextStyle(fontSize: 8, fontWeight: FontWeight.bold), + indicatorColor: Colors.white, + tabs: [ + Tab(text: "SERIES", icon: Icon(Icons.library_books, size: 18)), + Tab(text: "MERCH", icon: Icon(Icons.shopping_bag, size: 18)), + Tab(text: "CITIZENS", icon: Icon(Icons.people, size: 18)), + Tab(text: "INVITES", icon: Icon(Icons.vpn_key, size: 18)), + ], + ), + ), + body: const TabBarView( + children: [ + _ManageSeriesTab(), + _ManageMerchTab(), + _ManageUsersTab(), + _ManageInvitesTab(), + ], + ), + ), + ); + } +} + +// --- TAB 3: CITIZEN MODERATION (Energy & Ranks) --- +class _ManageUsersTab extends StatelessWidget { + const _ManageUsersTab(); + + void _showModeration(BuildContext context, DocumentSnapshot user) { + var d = user.data() as Map; + int rank = safeInt(d['rankLevel'] ?? 1); + bool ver = d['isVerified'] ?? (rank == 5); + bool ban = d['isBanned'] ?? false; + + showDialog( + context: context, + builder: (ctx) => StatefulBuilder( + builder: (ctx, setS) => AlertDialog( + backgroundColor: Colors.grey[900], + title: Text("MODERATING: ${d['username'] ?? 'Citizen'}"), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + DropdownButton( + value: rank, + isExpanded: true, + dropdownColor: Colors.black, + items: [1, 2, 3, 4, 5].map((v) => DropdownMenuItem(value: v, child: Text(getRankName(v)))).toList(), + onChanged: (v) => setS(() { + rank = v!; + if (rank == 5) ver = true; + }), + ), + SwitchListTile(title: const Text("Verified"), value: ver, activeThumbColor: kOnsolGold, onChanged: (v) => setS(() => ver = v)), + SwitchListTile(title: const Text("Exiled"), value: ban, activeThumbColor: Colors.red, onChanged: (v) => setS(() => ban = v)), + const SizedBox(height: 10), + + // --- ENERGY REFILL BUTTON (2/2) --- + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.orangeAccent, foregroundColor: Colors.black, minimumSize: const Size(double.infinity, 40)), + onPressed: () async { + await user.reference.update({ + 'energy': 2, + 'lastEnergyRefill': FieldValue.serverTimestamp() + }); + if (ctx.mounted) Navigator.pop(ctx); + }, + child: const Text("REFILL ENERGY (2/2)", style: TextStyle(fontWeight: FontWeight.bold)) + ), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("CANCEL")), + ElevatedButton( + onPressed: () async { + await user.reference.update({'rankLevel': rank, 'isVerified': ver, 'isBanned': ban}); + if (ctx.mounted) Navigator.pop(ctx); + }, + child: const Text("APPLY"), + ) + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + return ListView( + padding: const EdgeInsets.all(15), + children: snapshot.data!.docs.map((u) { + var d = u.data() as Map; + int r = safeInt(d['rankLevel'] ?? 1); + bool isBan = d['isBanned'] ?? false; + return Card( + color: Colors.grey[900], + child: ListTile( + leading: Icon(getRankIcon(r), color: isBan ? Colors.red : getRankColor(r)), + title: Row(children: [ + Text(d['username'] ?? 'Anonymous', style: TextStyle(color: isBan ? Colors.red : Colors.white)), + verifiedBadge(d['isVerified'] ?? (r == 5)) + ]), + subtitle: Text(isBan ? "EXILED" : getRankName(r)), + trailing: IconButton(icon: const Icon(Icons.shield, color: Colors.amber), onPressed: () => _showModeration(context, u)), + ), + ); + }).toList(), + ); + }, + ); + } +} + +// --- OTHER TABS --- + +class _ManageSeriesTab extends StatelessWidget { + const _ManageSeriesTab(); + void _add(BuildContext context) { + final t = TextEditingController(); + showDialog(context: context, builder: (ctx) => AlertDialog( + backgroundColor: Colors.grey[900], title: const Text("New Series"), + content: TextField(controller: t, decoration: const InputDecoration(hintText: "Series Title")), + actions: [ElevatedButton(onPressed: () { FirebaseFirestore.instance.collection('manga').add({'title': t.text, 'reads': 0, 'readingMode': 'RL', 'author': 'Artist', 'coverUrl': ''}); Navigator.pop(ctx); }, child: const Text("ADD"))], + )); + } + @override + Widget build(BuildContext context) { + return Scaffold(backgroundColor: Colors.transparent, floatingActionButton: FloatingActionButton(backgroundColor: Colors.white, child: const Icon(Icons.add, color: Colors.black), onPressed: () => _add(context)), body: StreamBuilder(stream: FirebaseFirestore.instance.collection('manga').snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) return const CircularProgressIndicator(); return ListView(padding: const EdgeInsets.all(15), children: snapshot.data!.docs.map((doc) => Card(color: Colors.grey[900], child: ListTile(title: Text(doc['title'] ?? 'Untitled'), trailing: IconButton(icon: const Icon(Icons.delete_outline, color: Colors.red), onPressed: () => doc.reference.delete())))).toList()); })); + } +} + +class _ManageMerchTab extends StatelessWidget { + const _ManageMerchTab(); + void _add(BuildContext context) { + final n = TextEditingController(); final p = TextEditingController(); final u = TextEditingController(); String cat = 'vault'; + showDialog(context: context, builder: (ctx) => StatefulBuilder(builder: (context, setS) => AlertDialog(backgroundColor: Colors.grey[900], title: const Text("New Item"), + content: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min, children: [TextField(controller: n, decoration: const InputDecoration(hintText: "Name")), TextField(controller: p, decoration: const InputDecoration(hintText: "Price")), TextField(controller: u, decoration: const InputDecoration(hintText: "Buy URL")), DropdownButton(value: cat, isExpanded: true, dropdownColor: Colors.black, items: ['vault', 'prints', 'merch'].map((s) => DropdownMenuItem(value: s, child: Text(s.toUpperCase()))).toList(), onChanged: (v) => setS(() => cat = v!))])), + actions: [ElevatedButton(onPressed: () { FirebaseFirestore.instance.collection('marketplace').add({'name': n.text, 'price': p.text, 'buyUrl': u.text, 'category': cat, 'imageUrl': ''}); Navigator.pop(ctx); }, child: const Text("ADD"))], + ))); + } + @override + Widget build(BuildContext context) { + return Scaffold(backgroundColor: Colors.transparent, floatingActionButton: FloatingActionButton(backgroundColor: kOnsolGold, child: const Icon(Icons.add_shopping_cart, color: Colors.black), onPressed: () => _add(context)), body: StreamBuilder(stream: FirebaseFirestore.instance.collection('marketplace').snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) return const CircularProgressIndicator(); return ListView(padding: const EdgeInsets.all(15), children: snapshot.data!.docs.map((doc) => Card(color: Colors.grey[900], child: ListTile(title: Text(doc['name'] ?? 'Item'), subtitle: Text(doc['price'] ?? ''), trailing: IconButton(icon: const Icon(Icons.delete_outline, color: Colors.red), onPressed: () => doc.reference.delete())))).toList()); })); + } +} + +class _ManageInvitesTab extends StatelessWidget { + const _ManageInvitesTab(); + @override + Widget build(BuildContext context) { + return Column(children: [ + const SizedBox(height: 20), + ElevatedButton(style: ElevatedButton.styleFrom(backgroundColor: Colors.white, foregroundColor: Colors.black), onPressed: () { + String code = List.generate(6, (i) => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Random().nextInt(30)]).join(); + FirebaseFirestore.instance.collection('invite_codes').doc(code).set({'isUsed': false, 'createdAt': FieldValue.serverTimestamp()}); + }, child: const Text("GENERATE INVITE")), + Expanded(child: StreamBuilder(stream: FirebaseFirestore.instance.collection('invite_codes').snapshots(), builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + var docs = snapshot.data!.docs; + docs.sort((a,b) { + var at = (a.data() as Map)['createdAt'] as Timestamp? ?? Timestamp.now(); + var bt = (b.data() as Map)['createdAt'] as Timestamp? ?? Timestamp.now(); + return bt.compareTo(at); + }); + return ListView(padding: const EdgeInsets.all(20), children: docs.map((doc) { + var d = doc.data() as Map; + return ListTile(title: Text(doc.id, style: const TextStyle(letterSpacing: 4, fontWeight: FontWeight.bold, color: Colors.white)), trailing: (d['isUsed'] ?? false) ? const Icon(Icons.check_circle, color: Colors.green) : const Icon(Icons.hourglass_empty, color: Colors.amber)); + }).toList()); + })) + ]); + } +} \ No newline at end of file diff --git a/lib/screens/artist/artist_hub.dart b/lib/screens/artist/artist_hub.dart new file mode 100644 index 0000000..fa46278 --- /dev/null +++ b/lib/screens/artist/artist_hub.dart @@ -0,0 +1,180 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/screens/artist/artist_series_manage_screen.dart'; +import 'package:onsolgo/screens/artist/artist_upcoming_screen.dart'; + +class ArtistHub extends StatefulWidget { + const ArtistHub({super.key}); + @override + State createState() => _ArtistHubState(); +} + +class _ArtistHubState extends State { + @override + Widget build(BuildContext context) { + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.amber[900], + title: const Text("ARTIST HUB"), + actions: [ + IconButton( + tooltip: 'Upcoming releases', + icon: const Icon(Icons.event_available), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const ArtistUpcomingScreen()), + ), + ), + ], + ), + body: Stack( + children: [ + Positioned.fill( + child: StreamBuilder( + stream: FirebaseFirestore.instance.collection('manga').where('authorId', isEqualTo: uid).snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + final docs = snapshot.data!.docs; + return CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Card( + margin: const EdgeInsets.fromLTRB(15, 15, 15, 8), + color: Colors.grey.shade900, + child: ListTile( + leading: const Icon(Icons.event_available, color: kOnsolGold), + title: const Text('MANAGE UPCOMING RELEASES'), + subtitle: const Text('Add, edit, or remove Soon tab teasers', style: TextStyle(fontSize: 11)), + trailing: const Icon(Icons.chevron_right, color: Colors.white54), + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const ArtistUpcomingScreen()), + ), + ), + ), + ), + if (docs.isEmpty) + SliverFillRemaining( + hasScrollBody: false, + child: Center( + child: Text( + 'No series assigned to your account yet.', + style: TextStyle(color: Colors.grey[500]), + ), + ), + ) + else + SliverPadding( + padding: const EdgeInsets.fromLTRB(15, 0, 15, 15), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => Card( + color: Colors.grey[900], + child: ListTile( + title: Text(docs[index]['title'] ?? 'Untitled'), + subtitle: const Text('Manage portfolio'), + onTap: () => _showOptions(context, docs[index]), + ), + ), + childCount: docs.length, + ), + ), + ), + ], + ); + }, + ), + ), + ], + ), + ); + } + + void _showOptions(BuildContext context, DocumentSnapshot series) { + showModalBottomSheet( + context: context, + backgroundColor: Colors.grey[900], + isScrollControlled: true, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))), + builder: (context) => SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.auto_stories, color: kOnsolGold), + title: const Text('SERIES & CHAPTERS'), + subtitle: const Text('Banner, library cover, chapters', style: TextStyle(fontSize: 11)), + onTap: () { + Navigator.pop(context); + Navigator.push( + context, + MaterialPageRoute(builder: (_) => ArtistSeriesManageScreen(series: series)), + ); + }, + ), + ListTile( + leading: const Icon(Icons.event_available, color: kOnsolGold), + title: const Text('UPCOMING RELEASES'), + subtitle: const Text('Manage Soon tab announcements', style: TextStyle(fontSize: 11)), + onTap: () { + Navigator.pop(context); + Navigator.push(context, MaterialPageRoute(builder: (_) => const ArtistUpcomingScreen())); + }, + ), + ListTile( + leading: const Icon(Icons.edit), + title: const Text('EDIT PORTFOLIO INFO'), + onTap: () { + Navigator.pop(context); + _editPortfolio(context, series); + }, + ), + const SizedBox(height: 20), + ], + ), + ), + ), + ); + } + + void _editPortfolio(BuildContext context, DocumentSnapshot series) { + final d = series.data() as Map; + final s = d['socials'] ?? {}; + final sC = TextEditingController(text: d['synopsis'] ?? ""); + final bC = TextEditingController(text: d['aboutArtist'] ?? ""); + final fbC = TextEditingController(text: s['facebook'] ?? ""); + final igC = TextEditingController(text: s['instagram'] ?? ""); + final xC = TextEditingController(text: s['twitter'] ?? s['x'] ?? ""); + final webC = TextEditingController(text: s['website'] ?? ""); + + showDialog(context: context, builder: (ctx) => AlertDialog( + backgroundColor: Colors.grey[900], title: const Text("Edit Portfolio"), + content: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min, children: [ + TextField(controller: sC, maxLines: 3, decoration: const InputDecoration(hintText: "Synopsis")), + TextField(controller: bC, maxLines: 3, decoration: const InputDecoration(hintText: "Artist Bio")), + TextField(controller: fbC, decoration: const InputDecoration(hintText: "Facebook URL")), + TextField(controller: igC, decoration: const InputDecoration(hintText: "Instagram URL")), + TextField(controller: xC, decoration: const InputDecoration(hintText: "X (Twitter) URL")), + TextField(controller: webC, decoration: const InputDecoration(hintText: "Personal website URL")), + ])), + actions: [ElevatedButton(onPressed: () { + series.reference.update({ + 'synopsis': sC.text, + 'aboutArtist': bC.text, + 'socials': { + 'facebook': fbC.text, + 'instagram': igC.text, + 'twitter': xC.text, + 'website': webC.text, + }, + }); + Navigator.pop(ctx); + }, child: const Text("SAVE"))], + )); + } +} \ No newline at end of file diff --git a/lib/screens/artist/artist_series_manage_screen.dart b/lib/screens/artist/artist_series_manage_screen.dart new file mode 100644 index 0000000..9dad174 --- /dev/null +++ b/lib/screens/artist/artist_series_manage_screen.dart @@ -0,0 +1,304 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_storage/firebase_storage.dart'; +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:onsolgo/core/constants.dart'; + +/// Series portfolio editor: cover (same view as chapter list context) and chapter removal. +class ArtistSeriesManageScreen extends StatefulWidget { + final DocumentSnapshot series; + + const ArtistSeriesManageScreen({super.key, required this.series}); + + @override + State createState() => _ArtistSeriesManageScreenState(); +} + +class _ArtistSeriesManageScreenState extends State { + /// null | 'cover' | 'banner' + String? _uploadingKind; + + Future _uploadSeriesCover() async { + final picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery, imageQuality: 70); + if (image == null) return; + setState(() => _uploadingKind = 'cover'); + try { + final ref = FirebaseStorage.instance.ref().child('series_covers').child('${widget.series.id}.jpg'); + await ref.putData(await image.readAsBytes(), SettableMetadata(contentType: 'image/jpeg')); + final url = await ref.getDownloadURL(); + await widget.series.reference.update({'coverUrl': url}); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Cover updated'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Cover upload failed: $e'))); + } + } finally { + if (mounted) setState(() => _uploadingKind = null); + } + } + + Future _uploadSeriesBanner() async { + final picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery, imageQuality: 72); + if (image == null) return; + setState(() => _uploadingKind = 'banner'); + try { + final ref = FirebaseStorage.instance.ref().child('series_banners').child('${widget.series.id}.jpg'); + await ref.putData(await image.readAsBytes(), SettableMetadata(contentType: 'image/jpeg')); + final url = await ref.getDownloadURL(); + await widget.series.reference.update({'bannerUrl': url}); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Banner updated'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Banner upload failed: $e'))); + } + } finally { + if (mounted) setState(() => _uploadingKind = null); + } + } + + Future _clearBanner() async { + final ok = await showDialog( + context: context, + builder: (c) => AlertDialog( + backgroundColor: Colors.grey[900], + title: const Text('Remove banner?', style: TextStyle(color: Colors.white)), + content: const Text( + 'The series page will use the tall cover image at the top until you add a banner again.', + style: TextStyle(color: Colors.white70), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('Cancel')), + TextButton( + onPressed: () => Navigator.pop(c, true), + child: const Text('Remove', style: TextStyle(color: Colors.redAccent)), + ), + ], + ), + ); + if (ok != true || !mounted) return; + try { + await widget.series.reference.update({'bannerUrl': FieldValue.delete()}); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Banner removed'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not remove banner: $e'))); + } + } + } + + Future _confirmDeleteChapter(DocumentSnapshot ch) async { + final cd = ch.data() as Map; + final numLabel = cd['chapterNumber']?.toString() ?? ch.id; + final ok = await showDialog( + context: context, + builder: (c) => AlertDialog( + backgroundColor: Colors.grey[900], + title: const Text('Remove chapter?', style: TextStyle(color: Colors.white)), + content: Text( + 'Delete chapter $numLabel from Firestore? This cannot be undone.', + style: const TextStyle(color: Colors.white70), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('Cancel')), + TextButton( + onPressed: () => Navigator.pop(c, true), + child: const Text('Delete', style: TextStyle(color: Colors.redAccent)), + ), + ], + ), + ); + if (ok != true || !mounted) return; + try { + await ch.reference.delete(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Chapter $numLabel removed'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not delete: $e'))); + } + } + } + + @override + Widget build(BuildContext context) { + final d = widget.series.data() as Map; + final title = d['title']?.toString() ?? 'Series'; + final cover = d['coverUrl']?.toString() ?? ''; + final banner = d['bannerUrl']?.toString() ?? ''; + final busy = _uploadingKind != null; + + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.amber[900], + title: Text(title.toUpperCase(), style: const TextStyle(fontSize: 14)), + ), + body: Stack( + children: [ + StreamBuilder( + stream: widget.series.reference.collection('chapters').orderBy('chapterNumber', descending: true).snapshots(), + builder: (context, chSnap) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + 'DETAIL PAGE BANNER', + style: TextStyle(fontSize: 11, color: Colors.grey, fontWeight: FontWeight.bold, letterSpacing: 1.2), + ), + const SizedBox(height: 6), + Text( + 'Wide image at the top when readers open this series (library grid still uses the cover below).', + style: TextStyle(fontSize: 11, color: Colors.grey[600], height: 1.3), + ), + const SizedBox(height: 10), + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: AspectRatio( + aspectRatio: 16 / 9, + child: banner.isEmpty + ? Container( + color: Colors.grey[850], + alignment: Alignment.center, + child: const Text('No banner yet', style: TextStyle(color: Colors.white38)), + ) + : CachedNetworkImage(imageUrl: banner, fit: BoxFit.cover, alignment: Alignment.center), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: busy ? null : _uploadSeriesBanner, + icon: const Icon(Icons.panorama_wide_angle_outlined, color: kOnsolGold), + label: const Text('UPDATE BANNER', style: TextStyle(color: kOnsolGold)), + style: OutlinedButton.styleFrom(side: const BorderSide(color: kOnsolGold)), + ), + ), + if (banner.isNotEmpty) ...[ + const SizedBox(width: 8), + IconButton( + tooltip: 'Remove banner', + onPressed: busy ? null : _clearBanner, + icon: const Icon(Icons.delete_outline, color: Colors.redAccent), + ), + ], + ], + ), + const SizedBox(height: 24), + const Text( + 'LIBRARY COVER', + style: TextStyle(fontSize: 11, color: Colors.grey, fontWeight: FontWeight.bold, letterSpacing: 1.2), + ), + const SizedBox(height: 10), + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: AspectRatio( + aspectRatio: 3 / 4, + child: cover.isEmpty + ? Container( + color: Colors.grey[850], + alignment: Alignment.center, + child: const Text('No cover', style: TextStyle(color: Colors.white38)), + ) + : CachedNetworkImage(imageUrl: cover, fit: BoxFit.cover, alignment: Alignment.topCenter), + ), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: busy ? null : _uploadSeriesCover, + icon: const Icon(Icons.photo_library_outlined, color: kOnsolGold), + label: const Text('UPDATE SERIES COVER', style: TextStyle(color: kOnsolGold)), + style: OutlinedButton.styleFrom(side: const BorderSide(color: kOnsolGold)), + ), + ], + ), + ), + ), + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(20, 0, 20, 8), + child: Text('CHAPTERS', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + ), + ), + if (chSnap.hasError) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text('Error: ${chSnap.error}', style: const TextStyle(color: Colors.redAccent)), + ), + ) + else if (!chSnap.hasData) + const SliverFillRemaining( + hasScrollBody: false, + child: Center(child: CircularProgressIndicator(color: kOnsolGold)), + ) + else if (chSnap.data!.docs.isEmpty) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + child: Center(child: Text('No chapters yet.', style: TextStyle(color: Colors.grey[500]))), + ), + ) + else + SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, i) { + final ch = chSnap.data!.docs[i]; + final cd = ch.data() as Map; + final thumb = cd['chapterCoverUrl']?.toString() ?? cover; + return Card( + color: Colors.grey[900], + margin: const EdgeInsets.only(bottom: 10), + child: ListTile( + leading: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: thumb.isEmpty + ? const SizedBox(width: 50, height: 50, child: ColoredBox(color: Colors.white10)) + : CachedNetworkImage(imageUrl: thumb, width: 50, height: 50, fit: BoxFit.cover), + ), + title: Text('Ch ${cd['chapterNumber']}', style: const TextStyle(color: Colors.white)), + trailing: IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.redAccent), + onPressed: () => _confirmDeleteChapter(ch), + ), + ), + ); + }, + childCount: chSnap.data!.docs.length, + ), + ), + ), + ], + ); + }, + ), + if (_uploadingKind != null) + const Positioned( + left: 0, + right: 0, + bottom: 0, + child: LinearProgressIndicator(minHeight: 3), + ), + ], + ), + ); + } +} diff --git a/lib/screens/artist/artist_upcoming_screen.dart b/lib/screens/artist/artist_upcoming_screen.dart new file mode 100644 index 0000000..9370e2c --- /dev/null +++ b/lib/screens/artist/artist_upcoming_screen.dart @@ -0,0 +1,406 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:firebase_storage/firebase_storage.dart'; +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; + +const String _kUpcomingCollection = 'upcoming'; +const String _kindNewSeries = 'new_series'; +const String _kindChapterDrop = 'chapter_drop'; + +/// Sentinel end date for Firestore ordering when "date TBD" (sorts after real dates). +final DateTime _kTbdSortDate = DateTime(2099, 12, 31, 23, 59); + +/// Artists manage teasers shown on the Soon tab. +class ArtistUpcomingScreen extends StatelessWidget { + const ArtistUpcomingScreen({super.key}); + + String _fmtDate(DateTime d) => '${d.month.toString().padLeft(2, '0')}/${d.day.toString().padLeft(2, '0')}/${d.year}'; + + Future _openEditor( + BuildContext context, { + DocumentSnapshot? existing, + }) async { + final uid = FirebaseAuth.instance.currentUser?.uid; + if (uid == null) return; + + final userSnap = await FirebaseFirestore.instance.collection('users').doc(uid).get(); + final userName = (userSnap.data()?['username'] as String?)?.trim() ?? 'Artist'; + + final mangaSnap = await FirebaseFirestore.instance.collection('manga').where('authorId', isEqualTo: uid).get(); + final mangaDocs = mangaSnap.docs; + + if (!context.mounted) return; + + String kind = existing?.get('kind') as String? ?? _kindNewSeries; + final titleCtrl = TextEditingController(text: existing?.get('seriesTitle') as String? ?? ''); + final descCtrl = TextEditingController(text: existing?.get('description') as String? ?? ''); + final chCtrl = TextEditingController( + text: existing != null && existing.get('chapterNumber') != null ? '${existing.get('chapterNumber')}' : '', + ); + String? mangaId = existing?.get('mangaId') as String?; + final existingTs = existing?.get('targetDate') as Timestamp?; + DateTime target = existingTs?.toDate() ?? DateTime.now().add(const Duration(days: 7)); + if (existing != null && (existing.get('dateTbd') as bool? ?? false)) { + target = DateTime.now().add(const Duration(days: 7)); + } + bool dateTbd = existing?.get('dateTbd') as bool? ?? false; + bool featured = existing?.get('featured') as bool? ?? false; + XFile? pickedCover; + final existingCoverUrl = existing?.get('teaserCoverUrl') as String?; + + await showDialog( + context: context, + builder: (ctx) => StatefulBuilder( + builder: (ctx, setS) => AlertDialog( + backgroundColor: Colors.grey[900], + title: Text(existing == null ? 'Announce release' : 'Edit announcement', style: const TextStyle(color: kOnsolGold, fontSize: 16)), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('Type', style: TextStyle(color: Colors.white70, fontSize: 12)), + const SizedBox(height: 4), + DropdownButton( + isExpanded: true, + dropdownColor: Colors.black87, + value: kind, + items: const [ + DropdownMenuItem(value: _kindNewSeries, child: Text('New series (coming soon)', style: TextStyle(color: Colors.white))), + DropdownMenuItem(value: _kindChapterDrop, child: Text('New chapter (existing series)', style: TextStyle(color: Colors.white))), + ], + onChanged: (v) => setS(() { + kind = v ?? _kindNewSeries; + if (kind == _kindNewSeries) mangaId = null; + }), + ), + if (kind == _kindChapterDrop) ...[ + const SizedBox(height: 12), + const Text('Series', style: TextStyle(color: Colors.white70, fontSize: 12)), + const SizedBox(height: 4), + DropdownButton( + isExpanded: true, + dropdownColor: Colors.black87, + value: mangaId != null && mangaDocs.any((d) => d.id == mangaId) ? mangaId : null, + hint: const Text('Select series', style: TextStyle(color: Colors.white54)), + items: mangaDocs + .map((d) => DropdownMenuItem(value: d.id, child: Text(d['title'] ?? d.id, style: const TextStyle(color: Colors.white)))) + .toList(), + onChanged: (v) => setS(() { + mangaId = v; + try { + final m = mangaDocs.firstWhere((d) => d.id == v); + titleCtrl.text = m['title'] ?? ''; + } catch (_) {} + }), + ), + const SizedBox(height: 8), + TextField( + controller: chCtrl, + keyboardType: TextInputType.number, + style: const TextStyle(color: Colors.white), + decoration: const InputDecoration( + labelText: 'Chapter # (optional)', + labelStyle: TextStyle(color: Colors.white70), + ), + ), + ] else ...[ + const SizedBox(height: 12), + TextField( + controller: titleCtrl, + style: const TextStyle(color: Colors.white), + decoration: const InputDecoration( + labelText: 'Series title', + labelStyle: TextStyle(color: Colors.white70), + hintText: 'Working title', + ), + ), + ], + const SizedBox(height: 12), + TextField( + controller: descCtrl, + maxLines: 4, + style: const TextStyle(color: Colors.white), + decoration: const InputDecoration( + labelText: 'Description (Soon tab)', + labelStyle: TextStyle(color: Colors.white70), + hintText: 'Teaser, synopsis, or hook for readers', + alignLabelWithHint: true, + ), + ), + const SizedBox(height: 12), + const Text('Teaser cover', style: TextStyle(color: Colors.white70, fontSize: 12)), + const SizedBox(height: 6), + Row( + children: [ + OutlinedButton.icon( + onPressed: () async { + final image = await ImagePicker().pickImage(source: ImageSource.gallery, imageQuality: 80); + if (image != null) setS(() => pickedCover = image); + }, + icon: const Icon(Icons.add_photo_alternate_outlined, color: kOnsolGold, size: 20), + label: const Text('Choose image', style: TextStyle(color: kOnsolGold, fontSize: 13)), + ), + ], + ), + if (pickedCover != null || (existingCoverUrl != null && existingCoverUrl.isNotEmpty)) ...[ + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: AspectRatio( + aspectRatio: 3 / 4, + child: pickedCover != null + ? FutureBuilder( + future: pickedCover!.readAsBytes(), + builder: (context, snap) { + if (!snap.hasData) return const ColoredBox(color: Colors.white10); + return Image.memory(snap.data!, fit: BoxFit.cover); + }, + ) + : CachedNetworkImage(imageUrl: existingCoverUrl!, fit: BoxFit.cover), + ), + ), + ], + const SizedBox(height: 12), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Highlight on Soon tab', style: TextStyle(color: Colors.white70, fontSize: 13)), + subtitle: const Text('Featured styling for this announcement', style: TextStyle(color: Colors.white38, fontSize: 11)), + value: featured, + activeThumbColor: kOnsolGold, + onChanged: (v) => setS(() => featured = v), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Release date TBD', style: TextStyle(color: Colors.white70, fontSize: 13)), + subtitle: const Text('No specific day yet — shows as “Date TBD”', style: TextStyle(color: Colors.white38, fontSize: 11)), + value: dateTbd, + activeThumbColor: kOnsolGold, + onChanged: (v) => setS(() => dateTbd = v), + ), + if (!dateTbd) + ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Release date', style: TextStyle(color: Colors.white70, fontSize: 12)), + subtitle: Text(_fmtDate(target), style: const TextStyle(color: kOnsolGold, fontWeight: FontWeight.bold)), + trailing: IconButton( + icon: const Icon(Icons.calendar_month, color: kOnsolGold), + onPressed: () async { + final picked = await showDatePicker( + context: ctx, + initialDate: target, + firstDate: DateTime.now().subtract(const Duration(days: 1)), + lastDate: DateTime.now().add(const Duration(days: 365 * 3)), + ); + if (picked != null) setS(() => target = picked); + }, + ), + ), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel', style: TextStyle(color: Colors.grey))), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: kOnsolGold, foregroundColor: Colors.black), + onPressed: () async { + final seriesTitle = titleCtrl.text.trim(); + if (seriesTitle.isEmpty) return; + if (kind == _kindChapterDrop && (mangaId == null || mangaId!.isEmpty)) return; + + num? chNum = num.tryParse(chCtrl.text.trim()); + final targetTs = dateTbd + ? Timestamp.fromDate(_kTbdSortDate) + : Timestamp.fromDate(DateTime(target.year, target.month, target.day, 23, 59)); + + final payload = { + 'kind': kind, + 'authorId': uid, + 'authorName': userName, + 'seriesTitle': seriesTitle, + 'mangaId': kind == _kindChapterDrop ? mangaId : null, + 'chapterNumber': chNum, + 'targetDate': targetTs, + 'dateTbd': dateTbd, + 'featured': featured, + 'description': descCtrl.text.trim(), + 'updatedAt': FieldValue.serverTimestamp(), + }; + + if (pickedCover == null && existingCoverUrl != null && existingCoverUrl.isNotEmpty) { + payload['teaserCoverUrl'] = existingCoverUrl; + } + + try { + if (existing == null) { + payload['createdAt'] = FieldValue.serverTimestamp(); + final docRef = FirebaseFirestore.instance.collection(_kUpcomingCollection).doc(); + await docRef.set(payload); + if (pickedCover != null) { + final ref = FirebaseStorage.instance.ref().child('upcoming_covers').child('${docRef.id}.jpg'); + await ref.putData(await pickedCover!.readAsBytes(), SettableMetadata(contentType: 'image/jpeg')); + final url = await ref.getDownloadURL(); + await docRef.update({'teaserCoverUrl': url}); + } + } else { + await existing.reference.update(payload); + if (pickedCover != null) { + final ref = FirebaseStorage.instance.ref().child('upcoming_covers').child('${existing.id}.jpg'); + await ref.putData(await pickedCover!.readAsBytes(), SettableMetadata(contentType: 'image/jpeg')); + final url = await ref.getDownloadURL(); + await existing.reference.update({'teaserCoverUrl': url}); + } + } + if (ctx.mounted) Navigator.pop(ctx); + } catch (e) { + if (ctx.mounted) { + ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(content: Text('Save failed: $e'))); + } + } + }, + child: Text(existing == null ? 'Publish' : 'Save'), + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final uid = FirebaseAuth.instance.currentUser?.uid ?? ''; + + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.amber[900], + title: const Text('UPCOMING RELEASES'), + ), + floatingActionButton: FloatingActionButton( + backgroundColor: kOnsolGold, + foregroundColor: Colors.black, + onPressed: uid.isEmpty ? null : () => _openEditor(context), + child: const Icon(Icons.add), + ), + body: uid.isEmpty + ? const Center(child: Text('Sign in', style: TextStyle(color: Colors.white54))) + : StreamBuilder( + stream: FirebaseFirestore.instance.collection(_kUpcomingCollection).where('authorId', isEqualTo: uid).snapshots(), + builder: (context, snapshot) { + if (snapshot.hasError) { + return Center(child: Text('Error: ${snapshot.error}', style: const TextStyle(color: Colors.redAccent))); + } + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: kOnsolGold)); + final docs = snapshot.data!.docs.toList() + ..sort((a, b) { + final ad = a.data() as Map; + final bd = b.data() as Map; + final af = ad['featured'] == true; + final bf = bd['featured'] == true; + if (af != bf) return af ? -1 : 1; + final atbd = ad['dateTbd'] == true; + final btbd = bd['dateTbd'] == true; + if (atbd != btbd) return atbd ? 1 : -1; + final ta = (ad['targetDate'] as Timestamp?)?.millisecondsSinceEpoch ?? 0; + final tb = (bd['targetDate'] as Timestamp?)?.millisecondsSinceEpoch ?? 0; + return ta.compareTo(tb); + }); + if (docs.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'No announcements yet.\nTap + to add a new series teaser or a chapter drop.', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.grey[500], height: 1.4), + ), + ), + ); + } + return ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: docs.length, + itemBuilder: (context, i) { + final doc = docs[i]; + final d = doc.data() as Map; + final kind = d['kind'] as String? ?? ''; + final title = d['seriesTitle'] ?? ''; + final dateTbd = d['dateTbd'] as bool? ?? false; + final ts = d['targetDate'] as Timestamp?; + final dateStr = dateTbd ? 'Date TBD' : (ts != null ? _fmtDate(ts.toDate()) : '—'); + final featured = d['featured'] == true; + final coverUrl = d['teaserCoverUrl'] as String?; + final subtitle = kind == _kindNewSeries + ? 'New series · $dateStr' + : 'New chapter · ${d['chapterNumber'] != null ? 'Ch ${d['chapterNumber']} · ' : ''}$dateStr'; + return Card( + color: Colors.grey[900], + margin: const EdgeInsets.only(bottom: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: featured ? kOnsolGold : Colors.white12, + width: featured ? 2 : 1, + ), + ), + child: ListTile( + isThreeLine: true, + leading: coverUrl != null && coverUrl.isNotEmpty + ? ClipRRect( + borderRadius: BorderRadius.circular(6), + child: CachedNetworkImage(imageUrl: coverUrl, width: 56, height: 80, fit: BoxFit.cover), + ) + : const Icon(Icons.image_outlined, color: Colors.white24), + title: Row( + children: [ + Expanded(child: Text(title, style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white))), + if (featured) + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: kOnsolGold.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(4), + ), + child: const Text('FEATURED', style: TextStyle(color: kOnsolGold, fontSize: 9, fontWeight: FontWeight.bold)), + ), + ], + ), + subtitle: Text(subtitle, style: TextStyle(color: Colors.grey[400], fontSize: 12)), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit, color: kOnsolGold, size: 20), + onPressed: () => _openEditor(context, existing: doc), + ), + IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.redAccent, size: 20), + onPressed: () async { + final ok = await showDialog( + context: context, + builder: (c) => AlertDialog( + backgroundColor: Colors.grey[900], + title: const Text('Remove?', style: TextStyle(color: Colors.white)), + actions: [ + TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.pop(c, true), child: const Text('Delete', style: TextStyle(color: Colors.red))), + ], + ), + ); + if (ok == true) await doc.reference.delete(); + }, + ), + ], + ), + ), + ); + }, + ); + }, + ), + ); + } +} diff --git a/lib/screens/auth/invite_signup_screen.dart b/lib/screens/auth/invite_signup_screen.dart new file mode 100644 index 0000000..b18e735 --- /dev/null +++ b/lib/screens/auth/invite_signup_screen.dart @@ -0,0 +1,66 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +class InviteSignupScreen extends StatefulWidget { + const InviteSignupScreen({super.key}); + @override + State createState() => _InviteSignupScreenState(); +} + +class _InviteSignupScreenState extends State { + final _code = TextEditingController(); + final _email = TextEditingController(); + final _pass = TextEditingController(); + final _user = TextEditingController(); + + void _processSignup() async { + final messenger = ScaffoldMessenger.of(context); + final nav = Navigator.of(context); + // 1. Check if Invite Code exists and is not used + var codeDoc = await FirebaseFirestore.instance.collection('invite_codes').doc(_code.text.trim()).get(); + + final codeData = codeDoc.data(); + if (codeDoc.exists && codeData != null && codeData['isUsed'] == false) { + try { + // 2. Create the User + UserCredential cred = await FirebaseAuth.instance.createUserWithEmailAndPassword( + email: _email.text.trim(), password: _pass.text.trim()); + + // 3. Create Firestore Profile + await FirebaseFirestore.instance.collection('users').doc(cred.user!.uid).set({ + 'username': _user.text.trim(), + 'role': 'reader', + 'rankLevel': 1, + 'uid': cred.user!.uid, + }); + + // 4. Burn the code + await codeDoc.reference.update({'isUsed': true}); + + if (context.mounted) nav.pop(); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } + } else { + messenger.showSnackBar(const SnackBar(content: Text("Invalid or Used Code"))); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text("REDEEM INVITATION")), + body: ListView( + padding: const EdgeInsets.all(32), + children: [ + TextField(controller: _code, decoration: const InputDecoration(labelText: "6-Digit Invite Code")), + TextField(controller: _user, decoration: const InputDecoration(labelText: "Choose Username")), + TextField(controller: _email, decoration: const InputDecoration(labelText: "Email")), + TextField(controller: _pass, decoration: const InputDecoration(labelText: "Password"), obscureText: true), + const SizedBox(height: 30), + ElevatedButton(onPressed: _processSignup, child: const Text("JOIN THE ORDER")), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/auth/login_screen.dart b/lib/screens/auth/login_screen.dart new file mode 100644 index 0000000..ba30be4 --- /dev/null +++ b/lib/screens/auth/login_screen.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/core/achievement_manager.dart'; +import 'package:onsolgo/screens/auth/tier_comparison_screen.dart'; +import 'package:cached_network_image/cached_network_image.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({super.key}); + @override + State createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final _email = TextEditingController(); + final _pass = TextEditingController(); + final _invite = TextEditingController(); + final _user = TextEditingController(); + bool _isSigningUp = false; + bool _loading = false; + + void _handleAuth() async { + setState(() => _loading = true); + final messenger = ScaffoldMessenger.of(context); + try { + if (_isSigningUp) { + var codeDoc = await FirebaseFirestore.instance.collection('invite_codes').doc(_invite.text.trim()).get(); + if (!codeDoc.exists || codeDoc['isUsed'] == true) throw "Invalid or Used Invite Code"; + + UserCredential cred = await FirebaseAuth.instance.createUserWithEmailAndPassword( + email: _email.text.trim(), password: _pass.text.trim()); + + await FirebaseFirestore.instance.collection('users').doc(cred.user!.uid).set({ + 'username': _user.text.trim(), + 'role': 'reader', + 'tier': 'free', // DEFAULT TIER + 'rankLevel': 1, + 'uid': cred.user!.uid, + 'streak': 1, + 'lastVisit': FieldValue.serverTimestamp(), + 'pagesRead': 0, + 'chaptersRead': 0, + 'energy': 2, + 'lastEnergyRefill': FieldValue.serverTimestamp(), + }); + + await codeDoc.reference.update({'isUsed': true}); + AchievementManager.unlock(cred.user!.uid, "initiate"); + } else { + await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email.text.trim(), password: _pass.text.trim()); + } + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(32), + child: Column( + children: [ + CachedNetworkImage(imageUrl: kOnsolBanner, height: 80), + const SizedBox(height: 40), + if (_isSigningUp) TextField(controller: _invite, decoration: const InputDecoration(labelText: "INVITE CODE", labelStyle: TextStyle(color: kOnsolGold))), + if (_isSigningUp) TextField(controller: _user, decoration: const InputDecoration(labelText: "CHOOSE USERNAME")), + TextField(controller: _email, decoration: const InputDecoration(labelText: "EMAIL")), + TextField(controller: _pass, decoration: const InputDecoration(labelText: "PASSWORD"), obscureText: true), + const SizedBox(height: 30), + _loading ? const CircularProgressIndicator(color: kOnsolGold) : ElevatedButton( + style: ElevatedButton.styleFrom(minimumSize: const Size(double.infinity, 50), backgroundColor: kOnsolGold, foregroundColor: Colors.black), + onPressed: _handleAuth, + child: Text(_isSigningUp ? "JOIN THE ORDER" : "ENTER THE ORDER") + ), + const SizedBox(height: 15), + + // NEW TIER COMPARISON LINK + TextButton( + onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const TierComparisonScreen())), + child: const Text("View Tier Benefits & Features", style: TextStyle(color: kOnsolGold, fontSize: 12, decoration: TextDecoration.underline)) + ), + + TextButton( + onPressed: () => setState(() => _isSigningUp = !_isSigningUp), + child: Text(_isSigningUp ? "Already a Citizen? Login" : "Redeem Invite", style: const TextStyle(color: Colors.white70)) + ), + ], + ), + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/auth/tier_comparison_screen.dart b/lib/screens/auth/tier_comparison_screen.dart new file mode 100644 index 0000000..a3bdb2e --- /dev/null +++ b/lib/screens/auth/tier_comparison_screen.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; +import 'package:onsolgo/core/constants.dart'; + +class TierComparisonScreen extends StatelessWidget { + const TierComparisonScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + elevation: 0, + title: const Text("ORDER TIERS", style: TextStyle(letterSpacing: 3, fontSize: 14)), + centerTitle: true, + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + const Text("CHOOSE YOUR STATUS", + style: TextStyle(color: kOnsolGold, fontSize: 22, fontWeight: FontWeight.bold, letterSpacing: 4)), + const SizedBox(height: 30), + + _buildTierCard( + context, + name: "READER", + price: "FREE", + color: Colors.grey, + features: [ + "Read current ManaA issues", + "Engage with Our Artists on the Social Feed", + "Shop the Merch Vault", + "Unlock Citizen Milestones", + ], + limitations: ["Standard Access (With Ads)", "Viewing only (No social posting)"], + ), + const SizedBox(height: 20), + _buildTierCard( + context, + name: "OGO+", + price: "\$2.99 / mo", + color: Colors.amber, + features: [ + "Ad-Free Access to ManaA issues", + "Post to the Social Feed: A Voice in the Community", + "Download your Favorite Chapters for Offline Reading", + + ], + ), + const SizedBox(height: 20), + _buildTierCard( + context, + name: "OGO+ MAX", + price: "\$4.99 / mo", + color: kOnsolGold, + features: [ + "Everything in OGO+ tier", + "The Archive (Access to back issues)", + "Exclusive Video Content", + ], + ), + const SizedBox(height: 40), + ], + ), + ), + ); + } + + Widget _buildTierCard(BuildContext context, { + required String name, required String price, required Color color, + required List features, List limitations = const [], + }) { + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.grey[900], + borderRadius: BorderRadius.circular(15), + border: Border.all(color: color.withValues(alpha: 0.4), width: 1), + ), + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(name, style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 20, letterSpacing: 2)), + Text(price, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), + ], + ), + const Divider(color: Colors.white10, height: 30), + ...features.map((f) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row(children: [ + Icon(Icons.check_circle, color: color, size: 16), + const SizedBox(width: 10), + Expanded(child: Text(f, style: const TextStyle(fontSize: 12, color: Colors.white70))), + ]), + )), + ...limitations.map((l) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row(children: [ + const Icon(Icons.info_outline, color: Colors.white24, size: 16), + const SizedBox(width: 10), + Expanded(child: Text(l, style: const TextStyle(fontSize: 12, color: Colors.white24))), + ]), + )), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/library/coming_soon.dart b/lib/screens/library/coming_soon.dart new file mode 100644 index 0000000..7d404aa --- /dev/null +++ b/lib/screens/library/coming_soon.dart @@ -0,0 +1,247 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/constants.dart'; + +/// Public feed of artist-scheduled releases (`upcoming` collection). +class ComingSoon extends StatelessWidget { + const ComingSoon({super.key}); + + String _fmtDate(DateTime d) => + '${d.month.toString().padLeft(2, '0')}/${d.day.toString().padLeft(2, '0')}/${d.year}'; + + String _countdown(Timestamp? ts, {required bool dateTbd}) { + if (dateTbd) return 'TBD'; + if (ts == null) return ''; + final t = ts.toDate(); + final now = DateTime.now(); + final endOfToday = DateTime(now.year, now.month, now.day, 23, 59, 59); + if (t.isBefore(endOfToday) && t.year == now.year && t.month == now.month && t.day == now.day) { + return 'Today'; + } + if (t.isBefore(now)) return 'Out now'; + final diff = t.difference(now); + if (diff.inDays >= 1) return 'in ${diff.inDays}d'; + if (diff.inHours >= 1) return 'in ${diff.inHours}h'; + return 'in ${diff.inMinutes}m'; + } + + int _sortUpcoming(DocumentSnapshot a, DocumentSnapshot b) { + final ad = a.data() as Map; + final bd = b.data() as Map; + final af = ad['featured'] == true; + final bf = bd['featured'] == true; + if (af != bf) return af ? -1 : 1; + final atbd = ad['dateTbd'] == true; + final btbd = bd['dateTbd'] == true; + if (atbd != btbd) return atbd ? 1 : -1; + final ta = (ad['targetDate'] as Timestamp?)?.millisecondsSinceEpoch ?? 0; + final tb = (bd['targetDate'] as Timestamp?)?.millisecondsSinceEpoch ?? 0; + return ta.compareTo(tb); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 56, 20, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.auto_awesome, size: 40, color: kOnsolGold), + const SizedBox(height: 12), + const Text( + 'THE SUN IS RISING', + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, letterSpacing: 3), + ), + const SizedBox(height: 8), + Text( + 'New series and chapter drops from ManaA artists.', + style: TextStyle(color: Colors.grey[400], letterSpacing: 0.5, height: 1.3), + ), + ], + ), + ), + ), + StreamBuilder( + stream: FirebaseFirestore.instance.collection('upcoming').limit(80).snapshots(), + builder: (context, snapshot) { + if (snapshot.hasError) { + return SliverFillRemaining( + child: Center(child: Text('Could not load schedule.\n${snapshot.error}', textAlign: TextAlign.center, style: const TextStyle(color: Colors.white54))), + ); + } + if (!snapshot.hasData) { + return const SliverFillRemaining(child: Center(child: CircularProgressIndicator(color: kOnsolGold))); + } + final docs = snapshot.data!.docs.toList()..sort(_sortUpcoming); + if (docs.isEmpty) { + return SliverFillRemaining( + child: Center( + child: Text('Check back soon for announcements.', style: TextStyle(color: Colors.grey[500])), + ), + ); + } + return SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 32), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, i) { + final doc = docs[i]; + final d = doc.data() as Map; + final kind = d['kind'] as String? ?? ''; + final seriesTitle = d['seriesTitle'] ?? 'Untitled'; + final artist = d['authorName'] ?? 'Artist'; + final dateTbd = d['dateTbd'] as bool? ?? false; + final ts = d['targetDate'] as Timestamp?; + final dateStr = dateTbd ? 'Date TBD' : (ts != null ? _fmtDate(ts.toDate()) : '—'); + final cd = _countdown(ts, dateTbd: dateTbd); + final ch = d['chapterNumber']; + final featured = d['featured'] == true; + final description = (d['description'] as String?)?.trim() ?? ''; + final coverUrl = (d['teaserCoverUrl'] as String?)?.trim() ?? ''; + + final headline = kind == 'new_series' + ? '$seriesTitle · $artist' + : 'New chapter · $seriesTitle${ch != null ? ' (Ch $ch)' : ''}'; + + final borderColor = featured ? kOnsolGold : kOnsolGold.withValues(alpha: 0.25); + final borderWidth = featured ? 2.5 : 1.0; + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all(color: borderColor, width: borderWidth), + boxShadow: featured + ? [ + BoxShadow( + color: kOnsolGold.withValues(alpha: 0.18), + blurRadius: 16, + spreadRadius: 0, + ), + ] + : null, + ), + child: Card( + color: featured ? const Color(0xFF1A1708) : Colors.grey[900], + margin: EdgeInsets.zero, + elevation: featured ? 4 : 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (featured) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Icon(Icons.star_rounded, color: kOnsolGold, size: 18), + const SizedBox(width: 6), + Text( + 'FEATURED DROP', + style: TextStyle( + color: kOnsolGold, + fontSize: 11, + fontWeight: FontWeight.w800, + letterSpacing: 1.4, + ), + ), + ], + ), + ), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (coverUrl.isNotEmpty) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(10), + child: CachedNetworkImage( + imageUrl: coverUrl, + width: 92, + height: 130, + fit: BoxFit.cover, + alignment: Alignment.topCenter, + ), + ), + const SizedBox(width: 14), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + headline, + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, height: 1.3, fontSize: 15), + ), + if (kind != 'new_series') ...[ + const SizedBox(height: 4), + Text(artist, style: TextStyle(color: Colors.grey[500], fontSize: 12)), + ], + if (description.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + description, + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: Colors.grey[300], fontSize: 13, height: 1.35), + ), + ], + ], + ), + ), + ], + ), + const SizedBox(height: 12), + Row( + children: [ + Icon(Icons.calendar_today, size: 14, color: Colors.grey[500]), + const SizedBox(width: 6), + Text( + dateTbd ? 'Target: to be announced' : 'Target: $dateStr', + style: TextStyle(color: Colors.grey[400], fontSize: 12), + ), + const Spacer(), + if (!dateTbd && cd.isNotEmpty) + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: kOnsolGold.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text(cd, style: const TextStyle(color: kOnsolGold, fontSize: 11, fontWeight: FontWeight.bold)), + ) + else if (dateTbd) + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + ), + child: const Text('SOON', style: TextStyle(color: Colors.white70, fontSize: 11, fontWeight: FontWeight.bold)), + ), + ], + ), + ], + ), + ), + ), + ); + }, + childCount: docs.length, + ), + ), + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/screens/library/library_grid.dart b/lib/screens/library/library_grid.dart new file mode 100644 index 0000000..a849227 --- /dev/null +++ b/lib/screens/library/library_grid.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/screens/library/series_detail.dart'; + +class LibraryGrid extends StatelessWidget { + const LibraryGrid({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: CustomScrollView( + slivers: [ + // THE BRAND BANNER + SliverToBoxAdapter( + child: Container( + color: Colors.black, + padding: const EdgeInsets.only(top: 50, bottom: 10), + child: CachedNetworkImage( + imageUrl: kOnsolBanner, + height: 100, + fit: BoxFit.contain + ), + ), + ), + + // THE MANAA GRID + StreamBuilder( + stream: FirebaseFirestore.instance.collection('manga').snapshots(), + builder: (context, snapshot) { + if (snapshot.hasError) return const SliverToBoxAdapter(child: Center(child: Text("Error Connection"))); + if (!snapshot.hasData) return const SliverToBoxAdapter(child: Center(child: CircularProgressIndicator())); + + final docs = snapshot.data!.docs; + + return SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverGrid( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + childAspectRatio: 0.65, + crossAxisSpacing: 16, + mainAxisSpacing: 20 + ), + delegate: SliverChildBuilderDelegate( + (context, index) => _MangaGridCard(manga: docs[index]), + childCount: docs.length, + ), + ), + ); + }, + ), + ], + ), + ); + } +} + +class _MangaGridCard extends StatelessWidget { + final QueryDocumentSnapshot manga; + const _MangaGridCard({required this.manga}); + + @override + Widget build(BuildContext context) { + final mData = manga.data() as Map; + + return GestureDetector( + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => SeriesDetail(manga: manga)) + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Stack( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: CachedNetworkImage( + imageUrl: mData['coverUrl'] ?? '', + fit: BoxFit.cover, + width: double.infinity, + alignment: Alignment.topCenter, + // Fix for desaturation: Ensure no filters are applied + placeholder: (context, url) => Container(color: Colors.grey[900]), + ), + ), + // READ COUNT OVERLAY + Positioned( + bottom: 8, left: 8, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(4) + ), + child: Row( + children: [ + const Icon(Icons.remove_red_eye, size: 12, color: Colors.white), + const SizedBox(width: 4), + Text( + "${safeInt(mData['reads'])}", + style: const TextStyle(fontSize: 10, color: Colors.white, fontWeight: FontWeight.bold) + ), + ], + ), + ), + ), + ], + ), + ), + const SizedBox(height: 10), + Text( + mData['title'].toString().toUpperCase(), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.white) + ), + Text( + mData['author'] ?? 'Artist', + style: const TextStyle(fontSize: 11, color: Colors.grey), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/library/series_detail.dart b/lib/screens/library/series_detail.dart new file mode 100644 index 0000000..f86aa17 --- /dev/null +++ b/lib/screens/library/series_detail.dart @@ -0,0 +1,161 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:google_mobile_ads/google_mobile_ads.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/screens/reader/reader_view.dart'; +import 'package:onsolgo/widgets/energy_user_chip.dart'; +import 'package:onsolgo/screens/auth/tier_comparison_screen.dart'; +import 'package:share_plus/share_plus.dart'; + +class SeriesDetail extends StatefulWidget { + final DocumentSnapshot manga; + const SeriesDetail({super.key, required this.manga}); + @override + State createState() => _SeriesDetailState(); +} + +class _SeriesDetailState extends State { + InterstitialAd? _interstitialAd; + + @override + void initState() { + super.initState(); + if (!kIsWeb) _loadInterstitial(); + } + + void _loadInterstitial() { + InterstitialAd.load(adUnitId: "ca-app-pub-3940256099942544/1033173712", request: const AdRequest(), adLoadCallback: InterstitialAdLoadCallback(onAdLoaded: (ad) => setState(() => _interstitialAd = ad), onAdFailedToLoad: (e) => debugPrint('$e'))); + } + + Future _handleAccess(DocumentSnapshot ch) async { + final uid = FirebaseAuth.instance.currentUser?.uid; if (uid == null) return; + final userDoc = await FirebaseFirestore.instance.collection('users').doc(uid).get(); + final uData = userDoc.data() ?? {}; + + // ELITE BYPASS: Rank 5 or Paid Tier + if ((uData['tier'] ?? 'free') != 'free' || safeInt(uData['rankLevel']) == 5 || (uData['isVerified'] ?? false)) { + _openReader(ch); return; + } + + int energy = safeInt(uData['energy'] ?? 2); + if (energy > 0) { + await userDoc.reference.update({'energy': energy - 1, 'lastEnergyRefill': FieldValue.serverTimestamp()}); + if (_interstitialAd != null && !kIsWeb) { + _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(onAdDismissedFullScreenContent: (ad) { ad.dispose(); _openReader(ch); _loadInterstitial(); }); + _interstitialAd!.show(); _interstitialAd = null; + } else { _openReader(ch); } + } else { _showExhausted(); } + } + + void _openReader(DocumentSnapshot ch) { Navigator.push(context, MaterialPageRoute(builder: (c) => ReaderView(manga: widget.manga, chapter: ch))); } + void _showExhausted() { showDialog(context: context, builder: (ctx) => AlertDialog(backgroundColor: Colors.grey[900], shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15), side: const BorderSide(color: Colors.red)), title: const Text("ENERGY DEPLETED"), content: const Text("Recharge in 24 hours or upgrade to OGO+."), actions: [ElevatedButton(onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const TierComparisonScreen())), child: const Text("UPGRADE"))])); } + + @override + Widget build(BuildContext context) { + final md = widget.manga.data() as Map; + final String cover = (md['coverUrl'] as String?)?.trim() ?? ''; + final String banner = (md['bannerUrl'] as String?)?.trim() ?? ''; + final bool hasBanner = banner.isNotEmpty; + final String heroUrl = hasBanner ? banner : cover; + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + + return Scaffold( + backgroundColor: Colors.black, extendBodyBehindAppBar: true, + appBar: AppBar(backgroundColor: Colors.transparent, elevation: 0, actions: [IconButton( + icon: const Icon(Icons.share_outlined), + onPressed: () => SharePlus.instance.share( + ShareParams(text: 'Check out ${md['title']} on ONSOL-GO!\n\n$kOnsolAppWebUrl'), + ), + )]), + body: SingleChildScrollView(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Stack(children: [ + CachedNetworkImage( + imageUrl: heroUrl, + width: double.infinity, + height: hasBanner ? 300 : 380, + fit: BoxFit.cover, + alignment: Alignment.topCenter, + placeholder: (context, url) => Container( + height: hasBanner ? 300 : 380, + color: Colors.grey[900], + ), + ), + Container( + height: hasBanner ? 301 : 381, + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Colors.transparent, Colors.black.withValues(alpha: 0.9), Colors.black], + ), + ), + ), + ]), + Padding( + padding: const EdgeInsets.all(20), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + if (hasBanner) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(md['title'] ?? '', style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)), + Text(md['author'] ?? '', style: const TextStyle(fontSize: 17, color: kOnsolGold)), + ], + ) + else ...[ + Text(md['title'] ?? '', style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold)), + Text(md['author'] ?? '', style: const TextStyle(fontSize: 18, color: kOnsolGold)), + ], + const SizedBox(height: 12), + Align(alignment: Alignment.centerLeft, child: EnergyUserChip(uid: uid)), + const SizedBox(height: 16), + const Text("SYNOPSIS", style: TextStyle(fontSize: 10, color: Colors.grey, fontWeight: FontWeight.bold, letterSpacing: 2)), + Text(md['synopsis'] ?? "No transmission recorded.", style: const TextStyle(color: Colors.white70, height: 1.4)), + const SizedBox(height: 30), + const Text("CHAPTERS", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + StreamBuilder( + stream: widget.manga.reference.collection('chapters').orderBy('chapterNumber', descending: true).snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const CircularProgressIndicator(); + return ListView.builder( + padding: const EdgeInsets.only(top: 10), shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + itemCount: snapshot.data!.docs.length, + itemBuilder: (c, i) => _ChapterTile(ch: snapshot.data!.docs[i], manga: widget.manga, uid: uid, onTap: () => _handleAccess(snapshot.data!.docs[i])), + ); + }, + ) + ]), + ), + ])), + ); + } +} + +class _ChapterTile extends StatelessWidget { + final DocumentSnapshot ch; final DocumentSnapshot manga; final String uid; final VoidCallback onTap; + const _ChapterTile({required this.ch, required this.manga, required this.uid, required this.onTap}); + + @override + Widget build(BuildContext context) { + final cd = ch.data() as Map; + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).collection('progress').doc(manga.id).snapshots(), + builder: (context, prog) { + double p = (prog.hasData && prog.data!.exists && prog.data!['lastChapter'] == cd['chapterNumber']) ? prog.data!['percent'] : 0.0; + return Card( + color: Colors.grey[900], margin: const EdgeInsets.only(bottom: 12), + child: ListTile( + onTap: onTap, + leading: ClipRRect(borderRadius: BorderRadius.circular(4), child: CachedNetworkImage(imageUrl: cd['chapterCoverUrl'] ?? (manga.data() as Map)['coverUrl'], width: 50, height: 50, fit: BoxFit.cover)), + title: Text("Ch ${cd['chapterNumber']}"), + subtitle: LinearProgressIndicator(value: p, color: kOnsolGold, backgroundColor: Colors.white10, minHeight: 2), + trailing: const Icon(Icons.bolt, color: Colors.orangeAccent, size: 18), + ), + ); + } + ); + } +} \ No newline at end of file diff --git a/lib/screens/library/trending_list.dart b/lib/screens/library/trending_list.dart new file mode 100644 index 0000000..69a3d9b --- /dev/null +++ b/lib/screens/library/trending_list.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/screens/library/series_detail.dart'; + +class TrendingList extends StatelessWidget { + const TrendingList({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text("🔥 WHAT'S HOT", style: TextStyle(letterSpacing: 2, fontWeight: FontWeight.bold)), + backgroundColor: Colors.black, + centerTitle: true, + ), + body: StreamBuilder( + stream: FirebaseFirestore.instance.collection('manga').orderBy('reads', descending: true).snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + final docs = snapshot.data!.docs; + return ListView.builder( + itemCount: docs.length, + padding: const EdgeInsets.all(16), + itemBuilder: (context, index) { + final m = docs[index]; + Color medalColor = (index == 0) ? kOnsolGold : (index == 1) ? const Color(0xFFC0C0C0) : (index == 2) ? const Color(0xFFCD7F32) : Colors.transparent; + + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: medalColor != Colors.transparent ? Border.all(color: medalColor, width: 2) : null + ), + child: Card( + color: Colors.grey[900], + margin: EdgeInsets.zero, + child: ListTile( + leading: ClipRRect(borderRadius: BorderRadius.circular(4), child: CachedNetworkImage(imageUrl: m['coverUrl'], width: 50, height: 70, fit: BoxFit.cover, alignment: Alignment.topCenter)), + title: Text(m['title'] ?? '', style: const TextStyle(fontWeight: FontWeight.bold)), + subtitle: Text("${m['reads'] ?? 0} Readers"), + trailing: Text("#${index + 1}", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: medalColor != Colors.transparent ? medalColor : Colors.white)), + onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context) => SeriesDetail(manga: m))), + ), + ), + ); + }, + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/market/market_hub.dart b/lib/screens/market/market_hub.dart new file mode 100644 index 0000000..109be1a --- /dev/null +++ b/lib/screens/market/market_hub.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/core/achievement_manager.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class MarketHub extends StatelessWidget { + const MarketHub({super.key}); + + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 3, + child: Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + title: const Text("ONSOL MARKET", style: TextStyle(letterSpacing: 2, fontWeight: FontWeight.bold)), + centerTitle: true, + bottom: const TabBar( + indicatorColor: kOnsolGold, labelColor: kOnsolGold, unselectedLabelColor: Colors.grey, + tabs: [Tab(text: "VAULT"), Tab(text: "PRINTS"), Tab(text: "MERCH")], + ), + ), + body: const TabBarView( + children: [ + _MarketCategoryView(categoryFilter: "vault"), + _MarketCategoryView(categoryFilter: "prints"), + _MarketCategoryView(categoryFilter: "merch"), + ], + ), + ), + ); + } +} + +class _MarketCategoryView extends StatelessWidget { + final String categoryFilter; + const _MarketCategoryView({required this.categoryFilter}); + + @override + Widget build(BuildContext context) { + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('marketplace').snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + final filtered = snapshot.data!.docs.where((d) => d['category'] == categoryFilter).toList(); + + return GridView.builder( + padding: const EdgeInsets.all(16), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.7, crossAxisSpacing: 16, mainAxisSpacing: 16), + itemCount: filtered.length, + itemBuilder: (context, index) { + var p = filtered[index].data() as Map; + return _ProductCard(name: p['name'], price: p['price'], imageUrl: p['imageUrl'], url: p['buyUrl']); + }, + ); + }, + ); + } +} + +class _ProductCard extends StatelessWidget { + final String name, price, imageUrl, url; + const _ProductCard({required this.name, required this.price, required this.imageUrl, required this.url}); + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration(color: Colors.grey[900], borderRadius: BorderRadius.circular(12)), + child: Column(children: [ + Expanded(child: ClipRRect(borderRadius: const BorderRadius.vertical(top: Radius.circular(12)), child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover))), + Padding(padding: const EdgeInsets.all(8.0), child: Column(children: [ + Text(name.toUpperCase(), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 10)), + Text(price, style: const TextStyle(color: kOnsolGold, fontSize: 12)), + const SizedBox(height: 5), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.white, foregroundColor: Colors.black, minimumSize: const Size(double.infinity, 30)), + onPressed: () { + launchUrl(Uri.parse(url)); + AchievementManager.unlock(FirebaseAuth.instance.currentUser!.uid, "first_acquisition"); + }, + child: const Text("ACQUIRE", style: TextStyle(fontSize: 10)), + ) + ])) + ]), + ); + } +} \ No newline at end of file diff --git a/lib/screens/profile/achievements_view.dart b/lib/screens/profile/achievements_view.dart new file mode 100644 index 0000000..c8f2bc3 --- /dev/null +++ b/lib/screens/profile/achievements_view.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:onsolgo/core/constants.dart'; + +class AchievementsView extends StatelessWidget { + const AchievementsView({super.key}); + + @override + Widget build(BuildContext context) { + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + title: const Text("CITIZEN ARCHIVE", + style: TextStyle(letterSpacing: 3, fontSize: 12, fontWeight: FontWeight.bold)), + centerTitle: true, + ), + body: StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).collection('achievements').snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: kOnsolGold)); + final unlocked = snapshot.data!.docs.map((d) => d.id).toList(); + + return ListView( + padding: const EdgeInsets.all(20), + children: [ + _buildCategory("ONBOARDING", "ACCOUNT", unlocked), + _buildCategory("READING PROGRESSION", "READING", unlocked), + _buildCategory("COMMUNITY & ENGAGEMENT", "COMMUNITY", unlocked), + _buildCategory("THE VAULT", "MARKET", unlocked), + _buildCategory("SUPPORT & INVESTMENT", "INVEST", unlocked), + _buildCategory("CONSISTENCY", "CONSISTENCY", unlocked), + _buildCategory("DISCOVERY", "DISCOVERY", unlocked), + _buildCategory("RARE / HIDDEN", "RARE", unlocked), + ], + ); + }, + ), + ); + } + + Widget _buildCategory(String title, String cat, List unlocked) { + final items = kAllAchievements.where((a) => a.category == cat).toList(); + if (items.isEmpty) return const SizedBox.shrink(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 15), + child: Text(title, + style: const TextStyle(color: kOnsolGold, fontWeight: FontWeight.bold, fontSize: 11, letterSpacing: 1.5)) + ), + GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + childAspectRatio: 2.1, + crossAxisSpacing: 10, + mainAxisSpacing: 10 + ), + itemCount: items.length, + itemBuilder: (c, i) { + final ach = items[i]; + bool done = unlocked.contains(ach.id); + + // NO CONST HERE: Colors are calculated at runtime + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: done ? kOnsolGold.withValues(alpha: 0.1) : Colors.grey[900], + borderRadius: BorderRadius.circular(10), + border: Border.all(color: done ? kOnsolGold : Colors.transparent, width: 0.5) + ), + child: Row( + children: [ + Icon(ach.icon, color: done ? kOnsolGold : Colors.grey, size: 22), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(ach.title, + style: TextStyle(fontSize: 9, fontWeight: FontWeight.bold, color: done ? Colors.white : Colors.grey)), + Text(ach.desc, + style: const TextStyle(fontSize: 7, color: Colors.white38), maxLines: 2), + ] + ) + ), + ] + ), + ); + }, + ), + ] + ); + } +} \ No newline at end of file diff --git a/lib/screens/profile/collection_view.dart b/lib/screens/profile/collection_view.dart new file mode 100644 index 0000000..5f8f2a3 --- /dev/null +++ b/lib/screens/profile/collection_view.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/screens/library/series_detail.dart'; + +class CollectionView extends StatelessWidget { + const CollectionView({super.key}); + + @override + Widget build(BuildContext context) { + final uid = FirebaseAuth.instance.currentUser?.uid; + + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar(title: const Text("YOUR VAULT"), backgroundColor: Colors.black), + body: StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).collection('user_collection').snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator()); + final items = snapshot.data!.docs; + if (items.isEmpty) return const Center(child: Text("Favorite a series to see it here.", style: TextStyle(color: Colors.grey))); + + return GridView.builder( + padding: const EdgeInsets.all(16), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, childAspectRatio: 0.65, crossAxisSpacing: 16, mainAxisSpacing: 16), + itemCount: items.length, + itemBuilder: (context, index) { + final doc = items[index]; + return GestureDetector( + onTap: () async { + DocumentSnapshot fullManga = await FirebaseFirestore.instance.collection('manga').doc(doc.id).get(); + if (context.mounted) Navigator.push(context, MaterialPageRoute(builder: (c) => SeriesDetail(manga: fullManga))); + }, + child: Column(children: [ + Expanded(child: ClipRRect(borderRadius: BorderRadius.circular(10), child: CachedNetworkImage(imageUrl: doc['coverUrl'], fit: BoxFit.cover))), + const SizedBox(height: 8), + Text(doc['title'].toString().toUpperCase(), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12)), + ]), + ); + }, + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/profile/profile_view.dart b/lib/screens/profile/profile_view.dart new file mode 100644 index 0000000..d56ac31 --- /dev/null +++ b/lib/screens/profile/profile_view.dart @@ -0,0 +1,154 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_storage/firebase_storage.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/screens/admin/admin_dashboard.dart'; +import 'package:onsolgo/screens/profile/collection_view.dart'; +import 'package:onsolgo/screens/profile/achievements_view.dart'; +import 'package:onsolgo/screens/artist/artist_hub.dart'; + +class ProfileView extends StatefulWidget { + const ProfileView({super.key}); + @override + State createState() => _ProfileViewState(); +} + +class _ProfileViewState extends State { + bool _isUploading = false; + Uint8List? _localBytes; + final ImagePicker _picker = ImagePicker(); + + Future _pickAndUpload(String uid) async { + try { + final XFile? image = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 40, maxWidth: 500); + if (image == null) return; + final bytes = await image.readAsBytes(); + setState(() { _localBytes = bytes; _isUploading = true; }); + + final ref = FirebaseStorage.instance.ref().child('avatars').child('$uid.jpg'); + await ref.putData(bytes, SettableMetadata(contentType: 'image/jpeg')); + + final downloadUrl = await ref.getDownloadURL(); + final sep = downloadUrl.contains('?') ? '&' : '?'; + final hashedUrl = '$downloadUrl${sep}t=${DateTime.now().millisecondsSinceEpoch}'; + await FirebaseFirestore.instance.collection('users').doc(uid).update({'pfpUrl': hashedUrl}); + } finally { if (mounted) setState(() => _isUploading = false); } + } + + @override + Widget build(BuildContext context) { + final String uid = FirebaseAuth.instance.currentUser?.uid ?? ""; + + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar(backgroundColor: Colors.black, elevation: 0, title: const Text("PROFILE")), + body: SafeArea( + child: StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData || !snapshot.data!.exists) return const Center(child: CircularProgressIndicator()); + + var data = snapshot.data!.data() as Map; + + // --- WEB-SAFE DATA PARSING --- + int rank = safeInt(data['rankLevel']); + final int energy = safeInt(data['energy'] ?? 2); + String role = data['role']?.toString().toLowerCase() ?? "reader"; + String tier = data['tier']?.toString().toLowerCase() ?? "free"; + String? pfp = data['pfpUrl']; + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 30), + // AVATAR + Center( + child: Stack(alignment: Alignment.center, children: [ + Container(width: 120, height: 120, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: getRankColor(rank), width: 3)), + child: ClipOval( + child: _localBytes != null + ? Image.memory(_localBytes!, fit: BoxFit.cover) + : (pfp != null && pfp.isNotEmpty + ? CachedNetworkImage( + imageUrl: pfp, + key: ValueKey(pfp), + fit: BoxFit.cover, + placeholder: (context, url) => const Center(child: SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2))), + errorWidget: (context, url, error) => const Icon(Icons.person, size: 60), + ) + : const Icon(Icons.person, size: 60)), + ), + ), + Positioned.fill(child: Material(color: Colors.transparent, child: InkWell(borderRadius: BorderRadius.circular(100), onTap: () => _pickAndUpload(uid)))), + if (_isUploading) + const Positioned.fill( + child: Center(child: SizedBox(width: 40, height: 40, child: CircularProgressIndicator(strokeWidth: 2, color: kOnsolGold))), + ), + ]), + ), + const SizedBox(height: 20), + Text(data['username']?.toString().toUpperCase() ?? "CITIZEN", style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + + // --- ENERGY BAR --- + const SizedBox(height: 8), + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + const Icon(Icons.local_fire_department, color: Colors.orange, size: 18), + Text("${data['streak'] ?? 0} DAY STREAK", style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold, fontSize: 12)), + const SizedBox(width: 15), + const Icon(Icons.bolt, color: Colors.orangeAccent, size: 18), + Text((tier != 'free' || rank == 5) ? "ENERGY: MAX" : "ENERGY: $energy/2", + style: const TextStyle(color: Colors.orangeAccent, fontWeight: FontWeight.bold, fontSize: 12)), + ]), + + Text(getRankName(rank), style: TextStyle(color: getRankColor(rank), letterSpacing: 2, fontWeight: FontWeight.bold)), + const SizedBox(height: 40), + + _MenuTile(icon: Icons.inventory_2_outlined, label: "VIEW VAULT", onTap: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const CollectionView()))), + _MenuTile(icon: Icons.emoji_events_outlined, label: "CITIZEN ARCHIVE", onTap: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const AchievementsView()))), + + const SizedBox(height: 40), + + // --- HUB BUTTONS (Stricter checks for Web) --- + if (rank == 5 || role == 'artist') + _HubBtn(label: "ARTIST HUB", color: Colors.amber[900]!, icon: Icons.palette, onTap: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const ArtistHub()))), + + const SizedBox(height: 10), + if (role == 'admin') + _HubBtn(label: "COMMAND CENTER", color: Colors.red[900]!, icon: Icons.admin_panel_settings, onTap: () => Navigator.push(context, MaterialPageRoute(builder: (c) => const AdminDashboard()))), + + const SizedBox(height: 30), + TextButton(onPressed: () => FirebaseAuth.instance.signOut(), child: const Text("TERMINATE SESSION", style: TextStyle(color: Colors.grey))), + ], + ), + ); + }, + ), + ), + ); + } +} + +class _HubBtn extends StatelessWidget { + final String label; final Color color; final IconData icon; final VoidCallback onTap; + const _HubBtn({required this.label, required this.color, required this.icon, required this.onTap}); + @override + Widget build(BuildContext context) { + return ListTile(onTap: onTap, tileColor: color.withValues(alpha: 0.15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), leading: Icon(icon, color: color), title: Text(label, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12))); + } +} + +class _MenuTile extends StatelessWidget { + final IconData icon; final String label; final VoidCallback onTap; + const _MenuTile({required this.icon, required this.label, required this.onTap}); + @override + Widget build(BuildContext context) { + return ListTile(leading: Icon(icon, color: Colors.white, size: 22), title: Text(label, style: const TextStyle(fontSize: 13)), trailing: const Icon(Icons.chevron_right, color: Colors.grey, size: 18), onTap: onTap); + } +} \ No newline at end of file diff --git a/lib/screens/reader/reader_view.dart b/lib/screens/reader/reader_view.dart new file mode 100644 index 0000000..7e3f093 --- /dev/null +++ b/lib/screens/reader/reader_view.dart @@ -0,0 +1,186 @@ +import 'package:flutter/material.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/core/share_helper.dart'; +import 'package:onsolgo/widgets/energy_user_chip.dart'; +import 'package:onsolgo/widgets/comments_sheet.dart'; + +class ReaderView extends StatefulWidget { + final DocumentSnapshot manga; + final DocumentSnapshot chapter; + const ReaderView({super.key, required this.manga, required this.chapter}); + @override + State createState() => _ReaderViewState(); +} + +class _ReaderViewState extends State { + final GlobalKey _readerKey = GlobalKey(); + bool _showUI = true; + int _curIdx = 0; + + DocumentReference _pageInteractionRef() { + return widget.manga.reference + .collection('chapters') + .doc(widget.chapter.id) + .collection('page_interactions') + .doc('${_curIdx + 1}'); + } + + Future _togglePageLike() async { + final uid = FirebaseAuth.instance.currentUser?.uid; + if (uid == null) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Sign in to react to pages'))); + return; + } + final pageRef = _pageInteractionRef(); + try { + await FirebaseFirestore.instance.runTransaction((txn) async { + final snap = await txn.get(pageRef); + List liked = []; + final raw = snap.data() as Map?; + if (snap.exists && raw != null) { + liked = List.from((raw['likedBy'] as List?)?.map((e) => e.toString()) ?? []); + } + final set = liked.toSet(); + if (set.contains(uid)) { + set.remove(uid); + } else { + set.add(uid); + } + final next = set.toList(); + final payload = {'likedBy': next, 'likes': next.length}; + if (snap.exists) { + txn.update(pageRef, payload); + } else { + txn.set(pageRef, payload); + } + }); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not update: $e'))); + } + } + } + + void _openPageComments() { + CommentsSheet.show( + context, + parent: _pageInteractionRef(), + title: 'Page ${_curIdx + 1} · Comments', + ); + } + + @override + Widget build(BuildContext context) { + final cD = widget.chapter.data() as Map; + final mD = widget.manga.data() as Map; + final total = safeInt(cD['pageCount']); + final uid = FirebaseAuth.instance.currentUser?.uid ?? ''; + + return Scaffold( + backgroundColor: Colors.black, + body: GestureDetector( + onTap: () => setState(() => _showUI = !_showUI), + child: Stack(children: [ + RepaintBoundary( + key: _readerKey, + child: Container( + color: Colors.black, + child: PageView.builder( + reverse: mD['readingMode'] == "RL", + itemCount: total, + onPageChanged: (idx) => setState(() => _curIdx = idx), + itemBuilder: (context, index) { + final url = "${cD['baseUrl']}PG-${(index + 1).toString().padLeft(3, '0')}.webp"; + return InteractiveViewer( + child: CachedNetworkImage(imageUrl: url, fit: BoxFit.contain), + ); + }, + ), + ), + ), + + if (_showUI) + Positioned( + top: 0, + left: 0, + right: 0, + child: AppBar( + backgroundColor: Colors.black.withValues(alpha: 0.7), + title: Text("PG ${_curIdx + 1}"), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 4, top: 4, bottom: 4), + child: EnergyUserChip(uid: FirebaseAuth.instance.currentUser?.uid ?? ''), + ), + IconButton( + icon: const Icon(Icons.share, color: kOnsolGold), + onPressed: () => OnsolShare.share( + _readerKey, + "Check out ${mD['title']} Ch ${cD['chapterNumber']} on ONSOL-GO!", + link: kOnsolShareChapterUrl(widget.manga.id, cD['chapterNumber']), + ), + ), + ], + ), + ), + + if (_showUI) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: Material( + color: Colors.black.withValues(alpha: 0.82), + child: SafeArea( + top: false, + child: StreamBuilder( + stream: _pageInteractionRef().snapshots(), + builder: (context, snap) { + final data = snap.data?.data() as Map?; + final likedBy = List.from( + (data?['likedBy'] as List?)?.map((e) => e.toString()) ?? [], + ); + final liked = uid.isNotEmpty && likedBy.contains(uid); + final count = likedBy.length; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + children: [ + IconButton( + icon: Icon( + liked ? Icons.favorite : Icons.favorite_border, + color: liked ? Colors.redAccent : Colors.white70, + ), + tooltip: 'Like this page', + onPressed: _togglePageLike, + ), + Text('$count', style: const TextStyle(color: Colors.white70, fontWeight: FontWeight.w600)), + const SizedBox(width: 4), + IconButton( + icon: const Icon(Icons.chat_bubble_outline, color: Colors.white70), + tooltip: 'Comments on this page', + onPressed: _openPageComments, + ), + const Text('Comment', style: TextStyle(color: Colors.white54, fontSize: 13)), + const Spacer(), + Text( + '${mD['title'] ?? ''} · Ch ${cD['chapterNumber']}', + style: TextStyle(color: Colors.grey[500], fontSize: 11), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ); + }, + ), + ), + ), + ), + ]), + ), + ); + } +} diff --git a/lib/screens/social/social_feed.dart b/lib/screens/social/social_feed.dart new file mode 100644 index 0000000..7a51a76 --- /dev/null +++ b/lib/screens/social/social_feed.dart @@ -0,0 +1,275 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:firebase_storage/firebase_storage.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:onsolgo/core/constants.dart'; +import 'package:onsolgo/core/share_helper.dart'; +import 'package:onsolgo/widgets/comments_sheet.dart'; + +class SocialFeed extends StatelessWidget { + const SocialFeed({super.key}); + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar(title: const Text("MANAA SOCIAL", style: TextStyle(letterSpacing: 2, fontWeight: FontWeight.bold)), centerTitle: true), + body: StreamBuilder( + stream: FirebaseFirestore.instance.collection('social_posts').orderBy('timestamp', descending: true).snapshots(), + builder: (context, snapshot) { + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: kOnsolGold)); + return ListView.builder( + itemCount: snapshot.data!.docs.length, + itemBuilder: (context, index) => _SocialPostCard(post: snapshot.data!.docs[index]), + ); + }, + ), + floatingActionButton: FloatingActionButton( + backgroundColor: kOnsolGold, child: const Icon(Icons.add_a_photo, color: Colors.black), + onPressed: () => showModalBottomSheet(context: context, isScrollControlled: true, backgroundColor: Colors.grey[900], builder: (c) => const _CreatePostSheet()), + ), + ); + } +} + +class _SocialPostCard extends StatefulWidget { + final QueryDocumentSnapshot post; + const _SocialPostCard({required this.post}); + + @override + State<_SocialPostCard> createState() => _SocialPostCardState(); +} + +class _SocialPostCardState extends State<_SocialPostCard> { + final GlobalKey _postKey = GlobalKey(); + + Future _confirmDeletePost() async { + final ok = await showDialog( + context: context, + builder: (c) => AlertDialog( + backgroundColor: Colors.grey[900], + title: const Text('Delete post?', style: TextStyle(color: Colors.white)), + content: const Text('This cannot be undone.', style: TextStyle(color: Colors.white70)), + actions: [ + TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.pop(c, true), child: const Text('Delete', style: TextStyle(color: Colors.redAccent))), + ], + ), + ); + if (ok != true || !mounted) return; + try { + await widget.post.reference.delete(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Post removed'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not delete: $e'))); + } + } + } + + Future _toggleLike() async { + final uid = FirebaseAuth.instance.currentUser?.uid; + if (uid == null) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Sign in to like posts'))); + return; + } + final ref = widget.post.reference; + try { + await FirebaseFirestore.instance.runTransaction((txn) async { + final snap = await txn.get(ref); + final data = snap.data() as Map?; + final liked = List.from((data?['likedBy'] as List?)?.map((e) => e.toString()) ?? []); + final set = liked.toSet(); + if (set.contains(uid)) { + set.remove(uid); + } else { + set.add(uid); + } + final next = set.toList(); + txn.update(ref, {'likedBy': next, 'likes': next.length}); + }); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Like failed: $e'))); + } + } + } + + @override + Widget build(BuildContext context) { + final post = widget.post; + final d = post.data() as Map; + final bool isVer = (d['isVerified'] ?? false) || (d['authorRank'] == "VERIFIED ManaA ARTIST"); + final uid = FirebaseAuth.instance.currentUser?.uid ?? ''; + final likedBy = List.from((d['likedBy'] as List?)?.map((e) => e.toString()) ?? []); + final liked = uid.isNotEmpty && likedBy.contains(uid); + final likeCount = likedBy.length; + final authorId = (d['authorId'] as String?) ?? ''; + + Widget card({required bool canDelete}) { + return RepaintBoundary( + key: _postKey, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + decoration: BoxDecoration(color: Colors.grey[900], borderRadius: BorderRadius.circular(15)), + child: Column(children: [ + StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(d['authorId']).snapshots(), + builder: (context, userSnap) { + String? livePfp; + if (userSnap.hasData && userSnap.data!.exists) { + var uD = userSnap.data!.data() as Map; + livePfp = uD.containsKey('pfpUrl') ? uD['pfpUrl'] : null; + } + return ListTile( + leading: CircleAvatar( + backgroundColor: Colors.black, + backgroundImage: livePfp != null ? NetworkImage(livePfp) : null, + child: livePfp == null ? const Icon(Icons.person, color: Colors.white24) : null), + title: Row(children: [ + Text(d['authorName'] ?? 'Citizen', style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white)), + verifiedBadge(isVer, size: 18), + ]), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (canDelete) + IconButton( + tooltip: 'Delete post', + icon: const Icon(Icons.delete_outline, size: 20, color: Colors.redAccent), + onPressed: _confirmDeletePost, + ), + IconButton( + icon: const Icon(Icons.share_outlined, size: 18, color: Colors.grey), + onPressed: () { + final raw = (d['content'] as String?)?.trim() ?? ''; + final caption = raw.isNotEmpty + ? raw + : 'Transmission from ${d['authorName'] ?? 'ONSOL-GO'}'; + OnsolShare.share( + _postKey, + caption, + link: kOnsolSharePostUrl(post.id), + ); + }, + ), + ], + ), + ); + }), + if (d['imageUrl'] != null) CachedNetworkImage(imageUrl: d['imageUrl'], width: double.infinity, fit: BoxFit.cover), + if (d['content'] != "") Padding(padding: const EdgeInsets.all(16), child: Text(d['content'] ?? '')), + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 12), + child: Row( + children: [ + IconButton( + icon: Icon(liked ? Icons.favorite : Icons.favorite_border, color: liked ? Colors.redAccent : Colors.white70, size: 22), + onPressed: _toggleLike, + tooltip: 'Like', + ), + Text('$likeCount', style: const TextStyle(color: Colors.white70, fontWeight: FontWeight.w600)), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.chat_bubble_outline, color: Colors.white70, size: 22), + onPressed: () => CommentsSheet.show(context, parent: post.reference, title: 'Comments'), + tooltip: 'Comments', + ), + const Text('Comment', style: TextStyle(color: Colors.white54, fontSize: 13)), + ], + ), + ), + ]), + ), + ); + } + + if (uid.isEmpty) { + return card(canDelete: false); + } + + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(), + builder: (context, meSnap) { + String? role; + if (meSnap.hasData && meSnap.data!.exists) { + role = (meSnap.data!.data() as Map?)?['role'] as String?; + } + final canDelete = uid == authorId || role == 'admin'; + return card(canDelete: canDelete); + }, + ); + } +} + +class _CreatePostSheet extends StatefulWidget { + const _CreatePostSheet(); + @override + State<_CreatePostSheet> createState() => _CreatePostSheetState(); +} + +class _CreatePostSheetState extends State<_CreatePostSheet> { + final _textC = TextEditingController(); Uint8List? _webImage; bool _posting = false; + Future _pick() async { + final picked = await ImagePicker().pickImage(source: ImageSource.gallery, imageQuality: 60); + if (picked != null) { final bytes = await picked.readAsBytes(); setState(() => _webImage = bytes); } + } + @override + Widget build(BuildContext context) { + return SafeArea(child: Padding(padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom + 20, left: 20, right: 20, top: 20), child: Column(mainAxisSize: MainAxisSize.min, children: [ + const Text("NEW ANNOUNCEMENT", style: TextStyle(fontWeight: FontWeight.bold, color: kOnsolGold)), + if (_webImage != null) Image.memory(_webImage!, height: 100), + TextField(controller: _textC, maxLines: 3, style: const TextStyle(color: Colors.white), decoration: const InputDecoration(hintText: "Speak to the Order...")), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + IconButton(onPressed: _pick, icon: const Icon(Icons.image, color: Colors.amber)), + _posting ? const CircularProgressIndicator() : ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: kOnsolGold, foregroundColor: Colors.black), + onPressed: () async { + final messenger = ScaffoldMessenger.of(context); + setState(() => _posting = true); + try { + final u = FirebaseAuth.instance.currentUser; + final uSnap = await FirebaseFirestore.instance.collection('users').doc(u?.uid).get(); + final raw = uSnap.data(); + if (u == null || !uSnap.exists || raw == null) { + messenger.showSnackBar( + const SnackBar(content: Text('Profile not found. Try signing in again.')), + ); + return; + } + final uMap = Map.from(raw as Map); + String? url; + if (_webImage != null) { + final ref = FirebaseStorage.instance.ref().child('social').child('${DateTime.now().millisecondsSinceEpoch}.jpg'); + await ref.putData(_webImage!, SettableMetadata(contentType: 'image/jpeg')); + url = await ref.getDownloadURL(); + } + await FirebaseFirestore.instance.collection('social_posts').add({ + 'authorId': u.uid, + 'authorName': uMap['username'], + 'authorPfp': uMap['pfpUrl'], + 'authorRank': getRankName(safeInt(uMap['rankLevel'])), + 'isVerified': safeInt(uMap['rankLevel']) == 5 || (uMap['isVerified'] ?? false), + 'content': _textC.text, + 'imageUrl': url, + 'likes': 0, + 'likedBy': [], + 'timestamp': FieldValue.serverTimestamp(), + }); + if (context.mounted) Navigator.pop(context); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text('Post failed: $e'))); + } finally { + if (mounted) setState(() => _posting = false); + } + }, + child: const Text("POST")), + ]), + ]))); + } +} \ No newline at end of file diff --git a/lib/widgets/comments_sheet.dart b/lib/widgets/comments_sheet.dart new file mode 100644 index 0000000..f28d6fc --- /dev/null +++ b/lib/widgets/comments_sheet.dart @@ -0,0 +1,177 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/material.dart'; +import 'package:onsolgo/core/constants.dart'; + +/// Bottom sheet: list comments under [parent] (`parent.collection('comments')`). +class CommentsSheet extends StatefulWidget { + final DocumentReference parent; + final String title; + + const CommentsSheet({ + super.key, + required this.parent, + this.title = 'Comments', + }); + + static Future show(BuildContext context, {required DocumentReference parent, String title = 'Comments'}) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.grey[900], + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => CommentsSheet(parent: parent, title: title), + ); + } + + @override + State createState() => _CommentsSheetState(); +} + +class _CommentsSheetState extends State { + final _textC = TextEditingController(); + bool _sending = false; + + @override + void dispose() { + _textC.dispose(); + super.dispose(); + } + + Future _send() async { + final uid = FirebaseAuth.instance.currentUser?.uid; + if (uid == null) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Sign in to comment'))); + return; + } + final text = _textC.text.trim(); + if (text.isEmpty) return; + + setState(() => _sending = true); + try { + final uSnap = await FirebaseFirestore.instance.collection('users').doc(uid).get(); + final name = (uSnap.data()?['username'] as String?)?.trim() ?? 'Citizen'; + await widget.parent.collection('comments').add({ + 'uid': uid, + 'authorName': name, + 'text': text, + 'timestamp': FieldValue.serverTimestamp(), + }); + _textC.clear(); + if (mounted) FocusScope.of(context).unfocus(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not post: $e'))); + } + } finally { + if (mounted) setState(() => _sending = false); + } + } + + @override + Widget build(BuildContext context) { + final uid = FirebaseAuth.instance.currentUser?.uid ?? ''; + final padBottom = MediaQuery.of(context).viewInsets.bottom; + + return Padding( + padding: EdgeInsets.only(bottom: padBottom), + child: SizedBox( + height: MediaQuery.of(context).size.height * 0.55, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 8, 8), + child: Row( + children: [ + Text(widget.title, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16)), + const Spacer(), + IconButton(icon: const Icon(Icons.close, color: Colors.white54), onPressed: () => Navigator.pop(context)), + ], + ), + ), + Expanded( + child: StreamBuilder( + stream: widget.parent.collection('comments').orderBy('timestamp', descending: false).snapshots(), + builder: (context, snap) { + if (snap.hasError) { + return Center(child: Text('Error: ${snap.error}', style: const TextStyle(color: Colors.redAccent))); + } + if (!snap.hasData) return const Center(child: CircularProgressIndicator(color: kOnsolGold)); + final docs = snap.data!.docs; + if (docs.isEmpty) { + return Center(child: Text('No comments yet.', style: TextStyle(color: Colors.grey[500]))); + } + return ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 12), + itemCount: docs.length, + itemBuilder: (context, i) { + final c = docs[i].data() as Map; + final author = c['authorName'] ?? 'Citizen'; + final text = c['text'] ?? ''; + final own = c['uid'] == uid; + return Card( + color: Colors.black54, + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + dense: true, + title: Text(author, style: const TextStyle(color: kOnsolGold, fontSize: 12, fontWeight: FontWeight.bold)), + subtitle: Text(text, style: const TextStyle(color: Colors.white70, fontSize: 14)), + trailing: own + ? IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.redAccent, size: 20), + onPressed: () async { + try { + await docs[i].reference.delete(); + } catch (e) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e'))); + } + } + }, + ) + : null, + ), + ); + }, + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _textC, + style: const TextStyle(color: Colors.white), + minLines: 1, + maxLines: 3, + decoration: InputDecoration( + hintText: 'Add a comment…', + hintStyle: TextStyle(color: Colors.grey[600]), + filled: true, + fillColor: Colors.black38, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + ), + onSubmitted: (_) => _send(), + ), + ), + const SizedBox(width: 8), + _sending + ? const Padding(padding: EdgeInsets.all(12), child: SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2))) + : IconButton.filled( + style: IconButton.styleFrom(backgroundColor: kOnsolGold, foregroundColor: Colors.black), + onPressed: _send, + icon: const Icon(Icons.send), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/energy_user_chip.dart b/lib/widgets/energy_user_chip.dart new file mode 100644 index 0000000..ecab7e4 --- /dev/null +++ b/lib/widgets/energy_user_chip.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:onsolgo/core/constants.dart'; + +/// Shows current reader energy (or MAX when unlimited) from `users/{uid}`. +class EnergyUserChip extends StatelessWidget { + final String uid; + const EnergyUserChip({super.key, required this.uid}); + + static bool _unlimited(Map u) { + return (u['tier'] ?? 'free') != 'free' || + safeInt(u['rankLevel']) == 5 || + (u['isVerified'] ?? false); + } + + @override + Widget build(BuildContext context) { + if (uid.isEmpty) return const SizedBox.shrink(); + return StreamBuilder( + stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(), + builder: (context, snap) { + if (!snap.hasData || !snap.data!.exists) return const SizedBox.shrink(); + final u = snap.data!.data() as Map; + final unlimited = _unlimited(u); + final e = safeInt(u['energy'] ?? 2); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Colors.orangeAccent.withValues(alpha: 0.5)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.bolt, color: unlimited ? kOnsolGold : Colors.orangeAccent, size: 18), + const SizedBox(width: 4), + Text( + unlimited ? 'ENERGY: MAX' : 'ENERGY: $e/2', + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12, + letterSpacing: 0.5, + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..5b64dfe --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "onsolgo") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.stnebula.onsolgo.onsolgo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..7299b5c --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..886932b --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..2ff86c6 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "onsolgo"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "onsolgo"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..fdd9bca --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,28 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import cloud_firestore +import file_selector_macos +import firebase_auth +import firebase_core +import firebase_storage +import share_plus +import sqflite_darwin +import url_launcher_macos +import webview_flutter_wkwebview + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FLTFirebaseFirestorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseFirestorePlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + FLTFirebaseAuthPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAuthPlugin")) + FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin")) + FLTFirebaseStoragePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseStoragePlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) + WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3e1c6aa --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* onsolgo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "onsolgo.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* onsolgo.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* onsolgo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/onsolgo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/onsolgo"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/onsolgo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/onsolgo"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/onsolgo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/onsolgo"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..6b8cebc --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..fbc0593 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = onsolgo + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.stnebula.onsolgo.onsolgo + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.stnebula.onsolgo. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..90e6190 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,994 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _flutterfire_internals: + dependency: transitive + description: + name: _flutterfire_internals + sha256: f698de6eb8a0dd7a9a931bbfe13568e8b77e702eb2deb13dd83480c5373e7746 + url: "https://pub.dev" + source: hosted + version: "1.3.68" + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + cached_network_image: + dependency: "direct main" + description: + name: cached_network_image + sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + cached_network_image_platform_interface: + dependency: transitive + description: + name: cached_network_image_platform_interface + sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829" + url: "https://pub.dev" + source: hosted + version: "4.1.1" + cached_network_image_web: + dependency: transitive + description: + name: cached_network_image_web + sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + cloud_firestore: + dependency: "direct main" + description: + name: cloud_firestore + sha256: "2e0a07b9905375fa17fba82ee1cd70df592907691e2f25a629823a021e49c1a2" + url: "https://pub.dev" + source: hosted + version: "6.2.0" + cloud_firestore_platform_interface: + dependency: transitive + description: + name: cloud_firestore_platform_interface + sha256: b82a35eb6a1bde9569df372f933fc5a01bcddef58c993d78f78c31d111fcd080 + url: "https://pub.dev" + source: hosted + version: "7.1.0" + cloud_firestore_web: + dependency: transitive + description: + name: cloud_firestore_web + sha256: "96bb9aec40d026b88737c1c426972ec435cac6b8d0f21af8eebb84fc09f100da" + url: "https://pub.dev" + source: hosted + version: "5.2.0" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" + firebase_auth: + dependency: "direct main" + description: + name: firebase_auth + sha256: "7421650001840aa63d3e7a59062bfa1a53febc52c7520e1effad0d325d6469cb" + url: "https://pub.dev" + source: hosted + version: "6.3.0" + firebase_auth_platform_interface: + dependency: transitive + description: + name: firebase_auth_platform_interface + sha256: "4f9103fe33f5a8cbe7b9bdae7a76e01cb67026b3fcaac5cf603a23685213f7cf" + url: "https://pub.dev" + source: hosted + version: "8.1.8" + firebase_auth_web: + dependency: transitive + description: + name: firebase_auth_web + sha256: "4173bfa41a8b6f0a791af99c61bead53fca819e32237c9336b84ebfbce44d7ae" + url: "https://pub.dev" + source: hosted + version: "6.1.4" + firebase_core: + dependency: "direct main" + description: + name: firebase_core + sha256: "2f988dab915efde3b3105268dbd69efce0e8570d767a218ccd914afd0c10c8cc" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + firebase_core_platform_interface: + dependency: transitive + description: + name: firebase_core_platform_interface + sha256: "0ecda14c1bfc9ed8cac303dd0f8d04a320811b479362a9a4efb14fd331a473ce" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + firebase_core_web: + dependency: transitive + description: + name: firebase_core_web + sha256: "1399ab1f0ac3b503d8a9be64a4c997fc066bbf33f701f42866e5569f26205ebe" + url: "https://pub.dev" + source: hosted + version: "3.5.1" + firebase_storage: + dependency: "direct main" + description: + name: firebase_storage + sha256: "2a9c9046eca3d4426eac73b671891666297a215019538e0af87eacec7e77ccf1" + url: "https://pub.dev" + source: hosted + version: "13.2.0" + firebase_storage_platform_interface: + dependency: transitive + description: + name: firebase_storage_platform_interface + sha256: "83f858784ebfdbe4d033d97c431ff67541d41266277ec290c169ce6c4bfda485" + url: "https://pub.dev" + source: hosted + version: "5.2.19" + firebase_storage_web: + dependency: transitive + description: + name: firebase_storage_web + sha256: "75003d7529cd458c93cfe12194773df1681d3b4722f70e5b4b4ff7b43ab8cd72" + url: "https://pub.dev" + source: hosted + version: "3.11.4" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_cache_manager: + dependency: transitive + description: + name: flutter_cache_manager + sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + google_mobile_ads: + dependency: "direct main" + description: + name: google_mobile_ads + sha256: "50549f6c945d7a445d53c04f34d025b1a1723fbd02719de9e67de432e2597f40" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + haptic_feedback: + dependency: "direct main" + description: + name: haptic_feedback + sha256: dcc2494994c41428823f8f2082fd17a4e89e372bd142e07681420cbfaf99dcad + url: "https://pub.dev" + source: hosted + version: "0.6.4+3" + hooks: + dependency: transitive + description: + name: hooks + sha256: e79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388 + url: "https://pub.dev" + source: hosted + version: "1.0.2" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "784210112be18ea55f69d7076e2c656a4e24949fa9e76429fe53af0c0f4fa320" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "66810af8e99b2657ee98e5c6f02064f69bb63f7a70e343937f70946c5f8c6622" + url: "https://pub.dev" + source: hosted + version: "0.8.13+16" + image_picker_for_web: + dependency: "direct main" + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.dev" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" + url: "https://pub.dev" + source: hosted + version: "0.17.6" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + octo_image: + dependency: transitive + description: + name: octo_image + sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "914a07484c4380e572998d30486e77e0d9cd2faec72fee268086d07bf7f302c9" + url: "https://pub.dev" + source: hosted + version: "2.3.0" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: ad3e91cabb7dc3c7687e0f4bdaf24fb192141d11bfbf9ddea7c26f3d4e8bfb5d + url: "https://pub.dev" + source: hosted + version: "13.0.0" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: ccf360f79b95993b083259d8f37baf20a47bcf8e2551ccebdc4f781b4d15e734 + url: "https://pub.dev" + source: hosted + version: "7.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + sqflite: + dependency: transitive + description: + name: sqflite + sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "881e28efdcc9950fd8e9bb42713dcf1103e62a2e7168f23c9338d82db13dec40" + url: "https://pub.dev" + source: hosted + version: "2.4.2+3" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "3bb000251e55d4a209aa0e2e563309dc9bb2befea2295fd0cec1f51760aac572" + url: "https://pub.dev" + source: hosted + version: "6.3.29" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + url: "https://pub.dev" + source: hosted + version: "2.4.2" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + webview_flutter: + dependency: transitive + description: + name: webview_flutter + sha256: a3da219916aba44947d3a5478b1927876a09781174b5a2b67fa5be0555154bf9 + url: "https://pub.dev" + source: hosted + version: "4.13.1" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: f560f57d0f529c1dcdaf4edc3a3217b099560622f9f4a10b6bdbb566553c61ea + url: "https://pub.dev" + source: hosted + version: "4.11.0" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: e15d8828e014291324a4d0cf6e272090167f4fa5673ffcf8fe446f4a4cd35861 + url: "https://pub.dev" + source: hosted + version: "3.24.3" + win32: + dependency: transitive + description: + name: win32 + sha256: "316d813e24518851c2682b1a57bc7e2e54e9c7b81493d48bef502fea0c17f841" + url: "https://pub.dev" + source: hosted + version: "6.0.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.11.1 <4.0.0" + flutter: ">=3.41.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..3c3ef7c --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,100 @@ +name: onsolgo +description: "The Onsol-GO! ManaA Collective Reader App" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.11.1 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + firebase_core: ^4.6.0 + cloud_firestore: ^6.2.0 + cached_network_image: ^3.4.1 + url_launcher: ^6.3.2 + firebase_auth: ^6.3.0 + haptic_feedback: ^0.6.4+3 + firebase_storage: ^13.2.0 + image_picker: ^1.2.1 + image_picker_for_web: ^3.1.1 + google_mobile_ads: ^8.0.0 + share_plus: ^13.0.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_launcher_icons: "^0.13.1" + flutter_lints: ^6.0.0 + +flutter_launcher_icons: + android: "launcher_icon" + ios: true + image_path: "assets/icon/app_icon.png" + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..8adaae3 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,65 @@ +{ + "version": 1, + "skills": { + "developing-genkit-dart": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "aa92490e4db5038730c629477ad968796f329040433625cf9b7bb13e26a859e3" + }, + "developing-genkit-go": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "b415d3697f81c182cbe3f560b09479b41d3c4dba1331c25231b95a56f212f7b8" + }, + "developing-genkit-js": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "2fa9adb27f7cfc4635decebea65222cd56e36b5de34781f7862be888504c04f4" + }, + "firebase-ai-logic": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "3b3d8994f2ac2e747a1f203488844a7e17b8a25c38e636b221903ae90e3b7c32" + }, + "firebase-app-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "7f0e0330510b4e6b06bcede472cebb183a491b8a0098f92d7563454c40d78050" + }, + "firebase-auth-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "ff79d278c0968f297d60f37532c32fd3b8bd9aad9c64b9f354585c701e80112a" + }, + "firebase-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "1a63ad98e772cbe4cded7eb8d83d0f8722f13f7b1a47087a8aa59a4080fc82bb" + }, + "firebase-data-connect": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "e7e35c29c4851d495a7417c4331666119d2492e914a08a8d006f1471a554e09f" + }, + "firebase-firestore-enterprise-native-mode": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "528bd602aa93a4409842a4e6f9888b8438521953253b0a629aeaf10603823bf9" + }, + "firebase-firestore-standard": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "ab2332607f40ae408e9c56e177b02fad55e071bfac4c2035a16ce0787768953e" + }, + "firebase-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "fb86fd4035e8e6379931faeb443557ac6f2e43fde04b397433f287e69b6532a9" + }, + "firestore-security-rules-auditor": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "1c2736882fd1c119914b46b11173976d71b425c0ac085a8afe9c58830af532e7" + } + } +} diff --git a/storage.rules b/storage.rules new file mode 100644 index 0000000..e9bdbe9 --- /dev/null +++ b/storage.rules @@ -0,0 +1,71 @@ +rules_version = '2'; + +service firebase.storage { + match /b/{bucket}/o { + + function isSignedIn() { + return request.auth != null; + } + + // Single Firestore read — Storage rules allow at most 2 Firestore document accesses + // per evaluation; pairing exists()+get() on users then on upcoming/manga exceeds that. + function isAdmin() { + return isSignedIn() + && firestore.get(/databases/(default)/documents/users/$(request.auth.uid)).data.role == 'admin'; + } + + function isReasonableImage() { + return request.resource != null + && request.resource.size < 15 * 1024 * 1024 + && request.resource.contentType.matches('image/.*'); + } + + // fileName like "{upcomingDocId}.jpg" — Firestore row must exist; get() fails if missing. + function ownsUpcomingCover(fileName) { + return isSignedIn() + && fileName.matches('.*\\.jpg') + && fileName.split('.').size() == 2 + && firestore.get(/databases/(default)/documents/upcoming/$(fileName.split('.')[0])).data.authorId == request.auth.uid; + } + + function mangaAuthorFromJpg(fileName) { + return isSignedIn() + && fileName.split('.').size() == 2 + && fileName.split('.')[1] == 'jpg' + && firestore.get(/databases/(default)/documents/manga/$(fileName.split('.')[0])).data.authorId == request.auth.uid; + } + + match /{allPaths=**} { + allow read: if true; + } + + match /avatars/{fileName} { + allow write: if isSignedIn() + && isReasonableImage() + && fileName == request.auth.uid + '.jpg'; + } + + match /social/{fileName} { + allow write: if isSignedIn() && isReasonableImage(); + } + + match /social_images/{fileName} { + allow write: if isSignedIn() && isReasonableImage(); + } + + match /series_covers/{fileName} { + allow write: if isReasonableImage() + && (mangaAuthorFromJpg(fileName) || isAdmin()); + } + + match /series_banners/{fileName} { + allow write: if isReasonableImage() + && (mangaAuthorFromJpg(fileName) || isAdmin()); + } + + match /upcoming_covers/{fileName} { + allow write: if isReasonableImage() + && (ownsUpcomingCover(fileName) || isAdmin()); + } + } +} diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..d94e28b --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,9 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Material smoke test', (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('ONSOL-GO!')))); + expect(find.text('ONSOL-GO!'), findsOneWidget); + }); +} diff --git a/tool/storage-cors.example.json b/tool/storage-cors.example.json new file mode 100644 index 0000000..9674f44 --- /dev/null +++ b/tool/storage-cors.example.json @@ -0,0 +1,8 @@ +[ + { + "origin": ["https://onsol-go.web.app", "http://localhost:5000", "http://localhost:8080"], + "method": ["GET", "HEAD"], + "maxAgeSeconds": 3600, + "responseHeader": ["Content-Type", "Authorization", "Content-Length", "x-goog-*"] + } +] diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..78d6ef4 --- /dev/null +++ b/web/index.html @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + ONSOL-GO! + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..78a3347 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Onsol-GO!", + "short_name": "Onsol-GO!", + "start_url": ".", + "display": "standalone", + "background_color": "#000000", + "theme_color": "#000000", + "description": "The ManaA Collective", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..3010750 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(onsolgo LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "onsolgo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..92dc522 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,32 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + CloudFirestorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CloudFirestorePluginCApi")); + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + FirebaseAuthPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseAuthPluginCApi")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); + FirebaseStoragePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseStoragePluginCApi")); + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..03f94f9 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,31 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + cloud_firestore + file_selector_windows + firebase_auth + firebase_core + firebase_storage + share_plus + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..ef4513e --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.stnebula.onsolgo" "\0" + VALUE "FileDescription", "onsolgo" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "onsolgo" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.stnebula.onsolgo. All rights reserved." "\0" + VALUE "OriginalFilename", "onsolgo.exe" "\0" + VALUE "ProductName", "onsolgo" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..f09df57 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"onsolgo", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_