extension-to-functions-codebase — скилл для Claude Code
Переносит Firebase Extension в локальную кодовую базу Cloud Functions или в отдельный npm-пакет. Помогает перевести триггеры с V1 на V2 и настроить декларативный доступ к IAM и API.
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a claude-codeЧто делает extension-to-functions-codebase
Скилл разбирает манифест extension.yaml и переносит логику расширения в functions/src/ либо оформляет её как npm-пакет. Параметры превращаются в типизированные геттеры вроде defineString и defineSecret из firebase-functions/params. Доступы к сервисам GCP описываются прямо в коде через requiresRole и requiresAPI. Ручные команды gcloud исключаются.
Инструмент переводит обработчики первого поколения на Cloud Functions V2: меняет события Firestore на onDocumentWritten, очереди на onTaskDispatched, а HTTP на onRequest. Для старых сигнатур применяется адаптер деструктуризации. Это исключает ручную правку обработчиков. События жизненного цикла переводятся в хуки afterFirstDeploy и afterRedeploy.
В коде нельзя вызывать .value() параметров на верхнем уровне модулей. Инициализацию клиентов скилл выносит строго внутрь onInit() или ленивых геттеров. Если нужно сохранить модель расходов V1 без конкурентности до 80 запросов, скилл выставляет параметр cpu: "gcf_gen1".
Какие задачи решает
- Перенести Firebase Extension в локальную кодовую базу functions/src/
- Собрать независимый npm-пакет на базе расширения Firebase под Node.js 22
- Обновить триггеры Cloud Functions с первого поколения на второе
- Заменить ручную настройку IAM и Google API на декларативные вызовы requiresRole и requiresAPI
Примеры запросов агенту
- Перенеси установленное расширение Firebase в кодовую базу Cloud Functions V2
- Сконвертируй исходники расширения в переиспользуемый npm-пакет с поддержкой Node 22
- Обнови триггеры расширения на Cloud Functions V2 и настрой хуки afterFirstDeploy
Как установить extension-to-functions-codebase
1Через Skills CLI (Vercel)
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a claude-code2Вручную: положить файлы
~/.claude/skills/extension-to-functions-codebase/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/extension-to-functions-codebase/
1Через Skills CLI (Vercel)
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a codex2Вручную: положить файлы
.agents/skills/extension-to-functions-codebase/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a cursor2Вручную: положить файлы
.cursor/skills/extension-to-functions-codebase/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install firebase/agent-skills extension-to-functions-codebase2Вручную: положить файлы
.github/skills/extension-to-functions-codebase/SKILL.md1Через Skills CLI (Vercel)
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a gemini-cli2Командой платформы
gemini skills install https://github.com/firebase/agent-skills --path skills/extension-to-functions-codebaseВручную: положить файлы
.devin/skills/extension-to-functions-codebase/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
Из того же набора10
Весь набор →Похожие
Вопросы о extension-to-functions-codebase
Как установить extension-to-functions-codebase в Claude Code?
Выполните в терминале команду npx skills add firebase/agent-skills --skill extension-to-functions-codebase -a claude-code.
Что делает скилл extension-to-functions-codebase?
Он переносит расширения Firebase в локальный проект Cloud Functions или npm-пакет с переходом на триггеры V2 и сохранением тестов Jest.
Как скилл предотвращает ошибки при чтении параметров окружения?
Скилл запрещает вызов .value() в глобальной области видимости модулей и переносит инициализацию SDK внутрь хука onInit() или ленивых геттеров.
Исходный текст
SKILL.md · Apache-2.0
---
name: extension-to-functions-codebase
description: Skill for converting an installed Firebase Extension (or extension source) into a standalone Cloud Functions for Firebase codebase or publishable npm package, including V1 to V2 trigger upgrades, lifecycle hooks, and declarative security
metadata:
author: Google LLC
category: Serverless
---
# Extension to Functions Codebase & npm Package Migration
## Overview
Migrates a Firebase Extension into either:
1. **A local Cloud Functions codebase** (`functions/src/` for app integration).
1. **A publishable npm package** (reusable open-source package exporting V2
functions).
Leverages native Cloud Functions features (declarative IAM, Parameterized
Config, SDK Lifecycle Hooks) and modernizes 1st Gen triggers to 2nd Gen using
the Destructuring Compatibility Shim.
______________________________________________________________________
## Target Migration Workflows
- **Target A: Local Functions Codebase** (End-User App Integration)
- Output: Code under `functions/src/`. Config in `.env`.
- Deployment: `firebase deploy --only functions`.
- **Target B: Publishable npm Package / Shareable Package**
- Output: Reusable npm package exporting V2 functions.
- Configuration: `package.json` specifying `exports` map,
`engines: { "node": ">=22" }`, and
`peerDependencies: { "firebase-functions": ">=6.0.0" }`.
- Usage: Consumers install package and re-export functions in `index.ts`
(`export * from "<package-name>"`).
______________________________________________________________________
## Core Rules & Constraints
### 1. Declarative IAM & APIs (Zero-Local-Overhead)
Use native SDK declarations instead of manual `gcloud` scripts or console
instructions:
- Use `requiresRole("roles/...")` for required GCP IAM permissions.
- Use `requiresAPI("service.googleapis.com", "Description")` for Google APIs.
### 2. Global Parameter Access Restriction
- **Never call `.value()` at top-level module load scope.**
- Initialize global SDK instances inside `onInit()` or lazy getters:
```typescript
import { defineString } from "firebase-functions/params";
import { onInit } from "firebase-functions/v2";
const dataset = defineString("DATASET_ID");
let client: BigQuery;
onInit(() => {
client = new BigQuery({ datasetId: dataset.value() });
});
```
### 3. V2 Concurrency & Cost Parity
V2 enables concurrency (up to 80 requests). To preserve V1 single-concurrency
pricing, set `cpu: "gcf_gen1"`.
______________________________________________________________________
## Step-by-Step Migration Execution
### Step 1: Inventory Extension Resources
1. **`extension.yaml`**:
- `params` → `defineString`, `defineInt`, `defineBoolean`, `defineSecret`.
- `apis` → `requiresAPI(...)`.
- `roles` → `requiresRole(...)`.
- `lifecycleEvents` → `afterFirstDeploy` & `afterRedeploy`.
- `resources` → Upgrade 1st Gen triggers to 2nd Gen (`onDocumentWritten`,
`onTaskDispatched`, `onRequest`).
1. **Files & Scripts**: Preserve devDependencies, test framework (`jest`), and
test scripts.
### Step 2: Configure `package.json`
- Set `name: "<package-name>"`, `engines: { "node": ">=22" }`.
- Set `peerDependencies`:
```json
"peerDependencies": {
"firebase-admin": "^11.0.0 || ^12.0.0",
"firebase-functions": ">=6.0.0"
}
```
- Configure `exports` map targeting ESM/CommonJS and TypeScript declarations
(`lib/index.js`, `lib/index.d.ts`).
### Step 3: Upgrade Triggers from V1 to V2
- Firestore: Use `onDocumentWritten` from `firebase-functions/v2/firestore`.
- Tasks: Use `onTaskDispatched` from `firebase-functions/v2/tasks`. Remove
`EXT_INSTANCE_ID` when enqueueing tasks.
- HTTP: Use `onRequest` from `firebase-functions/v2/https`.
- Apply Destructuring Compatibility Shim (`{ change, context }`,
`{ snapshot, context }`) where legacy 1st Gen handlers expect
`(change, context)`.
### Step 4: Convert Lifecycle Events
Map extension lifecycle events to SDK lifecycle hooks in `src/index.ts`:
- `onInstall` → `afterFirstDeploy({ task: { function: "initTask" } })`
- `onUpdate` / `onConfigure` →
`afterRedeploy({ task: { function: "setupTask" } })`
### Step 5: Package README & Export Instructions
Generate `README.md` containing:
1. Installation instructions (`npm install`).
1. Re-export snippet (`export * from "<package-name>"`).
1. Parameterized Configuration `.env` reference table.
1. What Changed (Extension vs Package) comparison table.
_Reminder: NEVER execute `npm publish`._
© Google LLC · Apache-2.0 · firebase/agent-skills