@gravitee/gamma-modules-sdk

中文文档
1.4.0发布于 2026/10/11Apache-2.0TypeScriptES Module近 30 天下载 2.5万

Shared contract between the Gamma host (gamma-console) and federated remote modules. Provides types, interfaces, and runtime stubs that are replaced at runtime by the host's real implementation via Module Federation.

原始使用文档
文档目录19 节
  1. Install
  2. Branching
  3. Architecture
  4. Remote usage
  5. Host implementation
  6. Module Federation config
  7. Exports
  8. Mock middleware ( /mock )
  9. Permissions domain
  10. License domain
  11. Environment domain
  12. Routing ( /routing )
  13. Development
  14. Prerequisites
  15. Commands
  16. Local development with gamma-console
  17. Contributing
  18. Releases
  19. License

@gravitee/gamma-modules-sdk

Shared contract between the Gamma host (gamma-console) and federated remote modules. Provides types, interfaces, and runtime stubs that are replaced at runtime by the host's real implementation via Module Federation.

Install

yarn add @gravitee/gamma-modules-sdk

Branching

main is the default branch and the release line. Branch feature work from main. Merges to main publish a stable version to npm via semantic-release.

Architecture

The SDK publishes four entry points:

Entry pointContentsUsed by
@gravitee/gamma-modules-sdkTypes + runtime stubsRemotes (and host barrel)
@gravitee/gamma-modules-sdk/typesInterfaces only (no runtime)Host implementation
@gravitee/gamma-modules-sdk/routingModule route helpersRemotes
@gravitee/gamma-modules-sdk/mockOpenAPI mock middlewareModule dev servers

Remote modules compile and bundle against the stubs. At runtime, the host provides its real implementation as a Module Federation singleton (additionalShared), replacing the stubs transparently.

Remote usage

import { useHasPermission, PermissionGate } from '@gravitee/gamma-modules-sdk';

function MyPage() {
  const canEdit = useHasPermission({ anyOf: ['environment-api-u'] });
  return (
    <PermissionGate anyOf={['environment-api-r']}>
      <p>Protected content</p>
    </PermissionGate>
  );
}

Host implementation

The host imports interfaces from the /types sub-path (which is not captured by the rspack alias or tsconfig path override) to enforce compile-time contract compliance:

import type { IPermissionService, PermissionScope } from '@gravitee/gamma-modules-sdk/types';

export class PermissionService implements IPermissionService {
  load(scope: PermissionScope, permissions: string[]): void {
    /* ... */
  }
  // TypeScript will error if any method is missing or has wrong signature
}

Module Federation config

Both host and remotes declare the SDK as a shared singleton:

additionalShared: [
  ['@gravitee/gamma-modules-sdk', { singleton: true, requiredVersion: false, strictVersion: false }],
],

The host's rspack config uses an exact-match alias so that sub-path imports (/types) resolve from node_modules:

resolve: {
  alias: {
    '@gravitee/gamma-modules-sdk$': gammaModulesSdkEntry, // note the $ for exact match
  },
},

Exports

Mock middleware (/mock)

OpenAPI-based mock middleware for standalone dev mode. Reads OpenAPI specs and serves mock responses from fixture files, so modules can run without a backend.

import { createOpenApiMockMiddleware } from '@gravitee/gamma-modules-sdk/mock';

// In rsbuild.config.ts setupMiddlewares:
createOpenApiMockMiddleware({
  moduleId: 'aim',
  specs: [join(__dirname, 'src/main/resources/openapi/openapi-catalog.yaml')],
  fixturesDir: join(__dirname, 'src/main/resources/catalog-fixtures'),
});

Handles GET list (pagination, ?q= search), GET by ID, sub-resource filtering, POST, PUT, DELETE, and the /gamma/ui/bootstrap endpoint.

Fixture files are named after the last path segment in the spec (e.g. models.json, mcp-servers.json).

Setting up standalone dev mode for a new module

  1. Add public/constants.json with { "gammaBaseURL": "/gamma" }
  2. Write your OpenAPI spec (or copy from an existing module)
  3. Add fixture JSON files matching your spec paths (e.g. models.json for /catalog/models)
  4. In rsbuild.config.ts:
import { createOpenApiMockMiddleware } from '@gravitee/gamma-modules-sdk/mock';

export default defineConfig(() => ({
  dev: {
    setupMiddlewares: [
      (middlewares) => {
        middlewares.unshift(
          createOpenApiMockMiddleware({
            moduleId: 'your-module',
            specs: [join(__dirname, 'path/to/openapi.yaml')],
            fixturesDir: join(__dirname, 'path/to/fixtures'),
          }),
        );
        return middlewares;
      },
    ],
  },
}));
  1. Run yarn serve and open http://localhost:3002

Permissions domain

Types: PermissionScope, PermissionCheck, UserRole, PermissionGateProps, UseHasPermissionOptions

Interfaces (from /types): IPermissionService, UseHasPermissionFn, PermissionGateFn, NormalizeCrudMapRecordFn, NormalizeOrgPermissionsFn

Stubs: PermissionService, permissionService, useHasPermission, PermissionGate, normalizeCrudMapRecord, normalizeOrganizationPermissionsFromRoles

License domain

Types: License

Interfaces (from /types): ILicenseService, UseHasFeatureFn, UseHasPackFn

Stubs: LicenseService, licenseService, useHasFeature, useHasPack

Environment domain

Types: Environment

Interfaces (from /types): IEnvironmentService, UseEnvironmentFn

Stubs: EnvironmentService, environmentService, useEnvironment

Routing (/routing)

Helpers for federated modules mounted under /environments/:envHrid/:moduleId/<routePath>: ModuleRouteConfig, useModuleRouting, useToHref, isRouteKey.

useModuleRouting(config) gives each route key one destination, used by both links and clicks:

  • pathForKey(key): the router path, for navigate() and <Link to>.
  • hrefForKey(key): the same path under the router's base path, for an <a href> that can be opened in a new tab.
  • navigateToKey(key): navigate(pathForKey(key)).

All three throw on a key missing from config.routes. hrefForKey runs while the nav is built, so an unknown key fails the render, not only the click: guard nav items that are not routes (e.g. external links) with isRouteKey.

A module that resolves its active item itself can still use useModuleRouting for these, and ignore activeNavKey. A module whose clicks go through a guard (e.g. an unsaved-changes prompt) should pass pathForKey(key) to its own guarded navigate instead of using navigateToKey, which calls React Router's navigate directly.

useToHref() returns a function that prefixes the router's base path to an absolute router path, for an <a href> or Graphene's breadcrumb toHref option. It needs no route config. The path must start with /, and a relative path throws: Graphene's option allows a relative to, but the hook cannot know whether navigate resolved it against the route or the URL, so give crumbs an absolute to (e.g. from pathForKey).

Graphene types nav item keys as string. isRouteKey narrows them to the module's route keys, so no cast is needed:

const { activeNavKey, hrefForKey, navigateToKey } = useModuleRouting(ROUTE_CONFIG);
const toHref = useToHref();
const groups = NAV_GROUPS.map((group) => ({
  ...group,
  items: group.items.map((item) =>
    isRouteKey(item.key, ROUTE_CONFIG.routeKeys) ? { ...item, href: hrefForKey(item.key) } : item,
  ),
}));
<SidebarNavigation
  groups={groups}
  activeItemKey={activeNavKey}
  onItemSelect={(key) => isRouteKey(key, ROUTE_CONFIG.routeKeys) && navigateToKey(key)}
/>;
buildLinearBreadcrumbs(navigate, segments, { toHref });

Development

Prerequisites

  • Node.js 24+ (see .nvmrc)
  • Yarn 4 (enabled via Corepack)

A full local Gamma stack is in docker/README.md. For Kind instead, use the gck Gamma context.

Commands

yarn install          # Install dependencies
yarn build            # Typecheck + Vite build
yarn test             # Vitest
yarn lint             # ESLint
yarn lint:fix:all     # ESLint --fix, Prettier write
yarn format:check     # Prettier check
yarn typecheck        # TypeScript only

For a full local check before a pull request, yarn lint:fix:all runs ESLint with fixes and Prettier to format the tree.

Local development with gamma-console

To iterate on SDK changes alongside the host or a remote without publishing:

# In this repo
yarn build
yarn link

# In gravitee-api-management
yarn link @gravitee/gamma-modules-sdk

Contributing

  1. Branch from main, make changes, and open a pull request
  2. Use Conventional Commits for commit messages
  3. On feature branches, CI runs lint, typecheck, build, test, and a branch-scoped npm prerelease
  4. Merges to main publish a stable version on npm via semantic-release

Releases

Releases are automated on main via semantic-release.

The version is derived from conventional commit messages:

  • fix: -> patch
  • feat: -> minor
  • feat!: or BREAKING CHANGE: -> major

License

Apache 2.0

版本与发布记录

@gravitee/gamma-modules-sdk 共发布 140 个版本,首次发布于 2026/04/23;过去 12 个月发布了 140 个版本。

版本发布日期距今
1.4.0latest2026/10/111 个月前
1.3.0-feat-ai-workspace-permission-scope.1239e66prerelease2026/10/111 个月前
1.3.02026/10/091 个月前
1.2.1-feat-found-314-href-for-key.347df182026/10/091 个月前
1.2.1-feat-found-314-href-for-key.6d58d3c2026/10/091 个月前
1.2.1-feat-found-314-href-for-key.86fd9402026/10/091 个月前

其他发布通道:alpha → 1.0.0-alpha.15,prerelease → 1.3.0-feat-ai-workspace-permission-scope.1239e66。

关于 @gravitee/gamma-modules-sdk 的常见问题

@gravitee/gamma-modules-sdk 是什么?

Shared contract between the Gamma host (gamma-console) and federated remote modules. Provides types, interfaces, and runtime stubs that are replaced at runtime by the host's real implementation via Module Federation.

如何安装 @gravitee/gamma-modules-sdk?

在项目目录运行 npm install @gravitee/gamma-modules-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=19)、react-dom(>=19)、react-router-dom(>=6)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gravitee/gamma-modules-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gravitee/gamma-modules-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gravitee/gamma-modules-sdk 可以商用吗?

@gravitee/gamma-modules-sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gravitee/gamma-modules-sdk 的下载量有多少?

根据 npm 官方下载统计,@gravitee/gamma-modules-sdk 在 2026/10/17 – 2026/11/15 这 30 天内被下载 24,948 次,日均约 832 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gravitee/gamma-modules-sdk 还在维护吗?

最新版本 1.4.0 发布于 2026/10/11(1 个月前);至今共发布 140 个版本,其中过去 12 个月发布了 140 个;首次发布于 2026/04/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。