@lovrabet/rabetbase-cli 2.5.13-beta.1 → 2.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -17
- package/lib/api/api-doc.js +3 -1
- package/lib/api/api-group.js +3 -1
- package/lib/api/fetch-model-list.js +1 -1
- package/lib/api/generate-api-file.js +8 -1
- package/lib/api/generate-sdk-config-file.js +1 -1
- package/lib/api/legacy-api-file.js +2 -1
- package/lib/api/model-registry-file.js +11 -1
- package/lib/api/model-registry-scaffold.js +2 -1
- package/lib/api/model-source.js +3 -1
- package/lib/auth/auth-server-ui.js +2 -1
- package/lib/auth/auth-server.js +5 -1
- package/lib/auth/constant.js +1 -1
- package/lib/auth/get-cookie.js +1 -1
- package/lib/auth/get-session-user.js +1 -1
- package/lib/auth/is-session-valid.js +1 -1
- package/lib/auth/login-success-html.js +3 -1
- package/lib/auth/logout.js +1 -1
- package/lib/cli-flags.js +1 -1
- package/lib/cli.js +5 -1
- package/lib/commands/api/generate.js +4 -1
- package/lib/commands/api/index.js +1 -1
- package/lib/commands/api/list.js +2 -1
- package/lib/commands/api/pull.js +10 -1
- package/lib/commands/api/shared.js +1 -1
- package/lib/commands/app/detail.js +1 -1
- package/lib/commands/app/index.js +1 -1
- package/lib/commands/app/list.js +5 -1
- package/lib/commands/app/members-list.js +1 -1
- package/lib/commands/app/remote-directory.js +1 -1
- package/lib/commands/app/shared.js +4 -1
- package/lib/commands/app-config/delete.js +2 -1
- package/lib/commands/app-config/get.js +2 -1
- package/lib/commands/app-config/index.js +1 -1
- package/lib/commands/app-config/list.js +2 -1
- package/lib/commands/app-config/set.js +3 -1
- package/lib/commands/app-config/shared.d.ts +9 -2
- package/lib/commands/app-config/shared.js +6 -1
- package/lib/commands/auth/index.js +1 -1
- package/lib/commands/bff/create.js +11 -1
- package/lib/commands/bff/delete.js +6 -1
- package/lib/commands/bff/detail.js +1 -1
- package/lib/commands/bff/index.js +1 -1
- package/lib/commands/bff/list.js +1 -1
- package/lib/commands/bff/logs.js +4 -1
- package/lib/commands/bff/pull.js +22 -1
- package/lib/commands/bff/push.js +16 -1
- package/lib/commands/bff/status.js +3 -1
- package/lib/commands/cli-skill/index.js +2 -1
- package/lib/commands/cli-update.js +7 -1
- package/lib/commands/codegen/index.js +1 -1
- package/lib/commands/codegen/sdk.js +1 -1
- package/lib/commands/codegen/sql.js +1 -1
- package/lib/commands/common/app-registry.js +4 -1
- package/lib/commands/common/app-selector.js +4 -1
- package/lib/commands/common/async-task.js +2 -1
- package/lib/commands/common/dry-run.js +1 -1
- package/lib/commands/common/flags.js +3 -1
- package/lib/commands/common/local-file.js +1 -1
- package/lib/commands/common/validate.js +1 -1
- package/lib/commands/config/delete.js +2 -1
- package/lib/commands/config/get.js +1 -1
- package/lib/commands/config/index.js +1 -1
- package/lib/commands/config/init.js +5 -1
- package/lib/commands/config/list.js +1 -1
- package/lib/commands/config/set.js +4 -1
- package/lib/commands/config/shared.js +2 -1
- package/lib/commands/dataset/batch-design.js +9 -1
- package/lib/commands/dataset/business-group-update.js +10 -1
- package/lib/commands/dataset/business-groups.js +1 -1
- package/lib/commands/dataset/capability.js +3 -1
- package/lib/commands/dataset/cross-relation-create.js +2 -1
- package/lib/commands/dataset/cross-relation-delete.js +1 -1
- package/lib/commands/dataset/cross-relation-list.js +2 -1
- package/lib/commands/dataset/cross-relation-shared.js +10 -1
- package/lib/commands/dataset/cross-relation-update.js +2 -1
- package/lib/commands/dataset/delete.js +6 -1
- package/lib/commands/dataset/design-context.js +1 -1
- package/lib/commands/dataset/design-start.js +1 -1
- package/lib/commands/dataset/design-status.js +1 -1
- package/lib/commands/dataset/design-sync-retry.js +1 -1
- package/lib/commands/dataset/design-sync-status.js +1 -1
- package/lib/commands/dataset/design-validate.js +1 -1
- package/lib/commands/dataset/detail.js +5 -1
- package/lib/commands/dataset/extend-update.js +7 -1
- package/lib/commands/dataset/field-restore.js +7 -1
- package/lib/commands/dataset/field-update.js +7 -1
- package/lib/commands/dataset/generate.js +19 -1
- package/lib/commands/dataset/index.js +3 -1
- package/lib/commands/dataset/list.js +2 -1
- package/lib/commands/dataset/operations.js +2 -1
- package/lib/commands/dataset/relation-audit.js +7 -1
- package/lib/commands/dataset/relation-create.js +3 -1
- package/lib/commands/dataset/relation-delete.js +3 -1
- package/lib/commands/dataset/relation-shared.js +21 -1
- package/lib/commands/dataset/relation-update.js +4 -1
- package/lib/commands/dataset/relations.js +7 -1
- package/lib/commands/dataset/rename.js +4 -1
- package/lib/commands/dataset/restore.js +7 -1
- package/lib/commands/dataset/user-deleted-field-list.js +3 -1
- package/lib/commands/db/analysis-batching.js +3 -1
- package/lib/commands/db/analyze-batch-plan.js +2 -1
- package/lib/commands/db/analyze-cancel.js +1 -1
- package/lib/commands/db/analyze-start.js +3 -1
- package/lib/commands/db/analyze-status.js +6 -1
- package/lib/commands/db/create.js +4 -1
- package/lib/commands/db/cross-db-analysis-shared.js +3 -1
- package/lib/commands/db/cross-db-analyze-latest.js +1 -1
- package/lib/commands/db/cross-db-analyze-start.js +2 -1
- package/lib/commands/db/cross-db-analyze-status.js +1 -1
- package/lib/commands/db/delete.js +3 -1
- package/lib/commands/db/detail.js +1 -1
- package/lib/commands/db/diff-refresh-start.js +1 -1
- package/lib/commands/db/diff-refresh-status.js +2 -1
- package/lib/commands/db/diff.js +3 -1
- package/lib/commands/db/index.js +2 -1
- package/lib/commands/db/list.js +2 -1
- package/lib/commands/db/shared.js +3 -1
- package/lib/commands/db/table-diff-shared.js +2 -1
- package/lib/commands/db/tables.js +2 -1
- package/lib/commands/db/test.js +2 -1
- package/lib/commands/db/update.js +4 -1
- package/lib/commands/deployment/index.js +1 -1
- package/lib/commands/deployment/sync-all.js +3 -1
- package/lib/commands/deployment/sync-jobs.js +2 -1
- package/lib/commands/deployment/sync-status.js +2 -1
- package/lib/commands/doctor.js +12 -1
- package/lib/commands/file/index.js +3 -1
- package/lib/commands/flow/create.js +2 -1
- package/lib/commands/flow/detail.js +3 -1
- package/lib/commands/flow/index.js +1 -1
- package/lib/commands/flow/list.js +2 -1
- package/lib/commands/flow/page-list.js +2 -1
- package/lib/commands/flow/publish.js +2 -1
- package/lib/commands/flow/runtime-resources-shared.js +3 -1
- package/lib/commands/flow/runtime-role-list.js +2 -1
- package/lib/commands/flow/runtime-role-user-list.js +2 -1
- package/lib/commands/flow/runtime-user-search.js +2 -1
- package/lib/commands/flow/shared.js +6 -1
- package/lib/commands/flow/update.js +4 -1
- package/lib/commands/flow/validate.js +2 -1
- package/lib/commands/instant-api-policy/current.js +1 -1
- package/lib/commands/instant-api-policy/index.js +1 -1
- package/lib/commands/instant-api-policy/init.js +2 -1
- package/lib/commands/instant-api-policy/publish.js +5 -1
- package/lib/commands/instant-api-policy/pull.js +2 -1
- package/lib/commands/instant-api-policy/revision.js +1 -1
- package/lib/commands/instant-api-policy/revisions.js +1 -1
- package/lib/commands/instant-api-policy/rollback.js +5 -1
- package/lib/commands/instant-api-policy/shared.js +5 -1
- package/lib/commands/instant-api-policy/validate.js +1 -1
- package/lib/commands/issue/context.js +1 -1
- package/lib/commands/issue/index.js +1 -1
- package/lib/commands/issue/nudge.js +2 -1
- package/lib/commands/issue/report.js +5 -1
- package/lib/commands/kb/create.js +5 -1
- package/lib/commands/kb/delete.js +5 -1
- package/lib/commands/kb/detail.js +1 -1
- package/lib/commands/kb/import-api.d.ts +3 -0
- package/lib/commands/kb/import-api.js +1 -0
- package/lib/commands/kb/import-resume.d.ts +2 -0
- package/lib/commands/kb/import-resume.js +2 -0
- package/lib/commands/kb/import-shared.d.ts +69 -0
- package/lib/commands/kb/import-shared.js +9 -0
- package/lib/commands/kb/import-status.d.ts +2 -0
- package/lib/commands/kb/import-status.js +1 -0
- package/lib/commands/kb/import.d.ts +2 -0
- package/lib/commands/kb/import.js +3 -0
- package/lib/commands/kb/index.js +1 -1
- package/lib/commands/kb/list.js +1 -1
- package/lib/commands/kb/search.js +3 -1
- package/lib/commands/kb/shared.js +9 -1
- package/lib/commands/kb/update.js +7 -1
- package/lib/commands/logs/index.js +2 -1
- package/lib/commands/menu/asset-update.js +8 -1
- package/lib/commands/menu/delete.js +15 -1
- package/lib/commands/menu/external-link-create.js +16 -1
- package/lib/commands/menu/external-link-update.js +10 -1
- package/lib/commands/menu/group-create.js +8 -1
- package/lib/commands/menu/group-update.js +6 -1
- package/lib/commands/menu/index.js +2 -1
- package/lib/commands/menu/list.js +1 -1
- package/lib/commands/menu/move.js +6 -1
- package/lib/commands/menu/regroup-start.js +11 -1
- package/lib/commands/menu/rename.js +9 -1
- package/lib/commands/menu/shared/compare-table.js +2 -1
- package/lib/commands/menu/shared/delete-plan.js +13 -1
- package/lib/commands/menu/shared/facts.js +5 -1
- package/lib/commands/menu/shared/index.js +1 -1
- package/lib/commands/menu/shared/inquirer.js +4 -1
- package/lib/commands/menu/shared/local-pages.js +5 -1
- package/lib/commands/menu/shared/logic.js +3 -1
- package/lib/commands/menu/shared/mutations.js +9 -1
- package/lib/commands/menu/shared/path.js +1 -1
- package/lib/commands/menu/shared/service.js +4 -1
- package/lib/commands/menu/shared/subapp-assets.js +4 -1
- package/lib/commands/menu/shared/sync-core.js +7 -1
- package/lib/commands/menu/shared/types.js +1 -1
- package/lib/commands/menu/shared/update-core.js +8 -1
- package/lib/commands/menu/shared/valid-url.js +1 -1
- package/lib/commands/menu/subapp-assets-status.js +1 -1
- package/lib/commands/menu/subapp-assets-update.js +7 -1
- package/lib/commands/menu/sync.js +7 -1
- package/lib/commands/menu/visibility-update.js +13 -1
- package/lib/commands/metric/contract.d.ts +8 -0
- package/lib/commands/metric/contract.js +5 -0
- package/lib/commands/metric/definition.d.ts +43 -0
- package/lib/commands/metric/definition.js +4 -0
- package/lib/commands/metric/delete.d.ts +2 -0
- package/lib/commands/metric/delete.js +3 -0
- package/lib/commands/metric/detail.d.ts +2 -0
- package/lib/commands/metric/detail.js +1 -0
- package/lib/commands/metric/example.d.ts +2 -0
- package/lib/commands/metric/example.js +1 -0
- package/lib/commands/metric/index.d.ts +2 -0
- package/lib/commands/metric/index.js +1 -0
- package/lib/commands/metric/list.d.ts +2 -0
- package/lib/commands/metric/list.js +2 -0
- package/lib/commands/metric/publication-diff.d.ts +8 -0
- package/lib/commands/metric/publication-diff.js +1 -0
- package/lib/commands/metric/publish.d.ts +2 -0
- package/lib/commands/metric/publish.js +4 -0
- package/lib/commands/metric/schema.d.ts +2 -0
- package/lib/commands/metric/schema.js +1 -0
- package/lib/commands/metric/shared.d.ts +14 -0
- package/lib/commands/metric/shared.js +2 -0
- package/lib/commands/metric/validate.d.ts +2 -0
- package/lib/commands/metric/validate.js +1 -0
- package/lib/commands/notification/config-create.js +4 -1
- package/lib/commands/notification/config-delete.js +4 -1
- package/lib/commands/notification/config-list.js +2 -1
- package/lib/commands/notification/config-update.js +4 -1
- package/lib/commands/notification/index.js +1 -1
- package/lib/commands/notification/shared.js +18 -1
- package/lib/commands/ocr/index.js +4 -1
- package/lib/commands/page/create.js +6 -1
- package/lib/commands/page/custom/detail.js +2 -1
- package/lib/commands/page/custom/list.js +2 -1
- package/lib/commands/page/custom/publish.js +3 -1
- package/lib/commands/page/custom/shared.js +3 -1
- package/lib/commands/page/custom/syntax.js +2 -1
- package/lib/commands/page/custom/update.js +3 -1
- package/lib/commands/page/data-list-status.js +2 -1
- package/lib/commands/page/generate-start.js +5 -1
- package/lib/commands/page/generate-status.js +4 -1
- package/lib/commands/page/index.js +2 -1
- package/lib/commands/page/pull.js +6 -1
- package/lib/commands/page/push.js +11 -1
- package/lib/commands/page/relation-audit.js +15 -1
- package/lib/commands/page/restore.js +5 -1
- package/lib/commands/page/shared.js +16 -1
- package/lib/commands/page/sync.js +2 -1
- package/lib/commands/project/api-architecture-upgrade.js +11 -1
- package/lib/commands/project/create/enhanced-guided-create.js +2 -1
- package/lib/commands/project/create/format-elapsed.js +1 -1
- package/lib/commands/project/create/main.js +13 -1
- package/lib/commands/project/create/materialize-project-template.js +12 -1
- package/lib/commands/project/create/project-name.js +1 -1
- package/lib/commands/project/create/project-template-archive.js +5 -1
- package/lib/commands/project/create/project-template-path.js +1 -1
- package/lib/commands/project/create/use-copy-project-template.js +2 -1
- package/lib/commands/project/create/use-format-code.js +1 -1
- package/lib/commands/project/create/use-install-dependencies.js +1 -1
- package/lib/commands/project/domain-routing-sync.js +1 -1
- package/lib/commands/project/index.js +4 -1
- package/lib/commands/project/upgrade.js +7 -1
- package/lib/commands/registry.js +10 -1
- package/lib/commands/role/delete.js +2 -1
- package/lib/commands/role/detail.js +1 -1
- package/lib/commands/role/index.js +1 -1
- package/lib/commands/role/list.js +2 -1
- package/lib/commands/role/shared.js +8 -1
- package/lib/commands/role/update.js +3 -1
- package/lib/commands/role/user-add.js +2 -1
- package/lib/commands/role/user-remove.js +2 -1
- package/lib/commands/role/user-resolve.js +1 -1
- package/lib/commands/rule/get.js +1 -1
- package/lib/commands/rule/index.js +1 -1
- package/lib/commands/rule/list.js +1 -1
- package/lib/commands/rule/set.js +7 -1
- package/lib/commands/rule/shared.js +4 -1
- package/lib/commands/run/index.js +5 -1
- package/lib/commands/schema.js +1 -1
- package/lib/commands/sql/create.js +7 -1
- package/lib/commands/sql/delete.js +4 -1
- package/lib/commands/sql/detail.js +1 -1
- package/lib/commands/sql/exec.js +1 -1
- package/lib/commands/sql/index.js +1 -1
- package/lib/commands/sql/list.js +2 -1
- package/lib/commands/sql/pull.js +10 -1
- package/lib/commands/sql/push.js +9 -1
- package/lib/commands/sql/shared.js +5 -1
- package/lib/commands/sql/status.js +3 -1
- package/lib/commands/sql/validate.js +5 -1
- package/lib/commands/task/index.js +1 -1
- package/lib/commands/task/status.js +2 -1
- package/lib/commands/tenant/index.js +1 -1
- package/lib/commands/tenant/members-list.js +2 -1
- package/lib/commands/tenant/shared.js +2 -1
- package/lib/commands/user-account/dingding-sandbox-bind.js +2 -1
- package/lib/commands/user-account/feishu-bind.js +2 -1
- package/lib/commands/user-account/index.js +1 -1
- package/lib/commands/workspace/add.js +1 -1
- package/lib/commands/workspace/index.js +7 -1
- package/lib/commands/workspace/remove.js +1 -1
- package/lib/config/domain-config.js +8 -1
- package/lib/config/project-domain-routing.js +3 -1
- package/lib/config/region-config.js +2 -1
- package/lib/config/schema.js +7 -1
- package/lib/constant/cdn.js +2 -1
- package/lib/constant/cli.js +8 -1
- package/lib/constant/defaults.js +1 -1
- package/lib/constant/domain.js +4 -1
- package/lib/constant/env.js +1 -1
- package/lib/constant/output.js +1 -1
- package/lib/constant/paths.js +1 -1
- package/lib/constant/region.js +1 -1
- package/lib/constant/risk.js +1 -1
- package/lib/constant/routing-profile.js +1 -1
- package/lib/context/app-resolver.js +7 -1
- package/lib/context/auth-resolver.js +1 -1
- package/lib/context/config-loader.js +7 -1
- package/lib/context.js +9 -1
- package/lib/core/alias-resolver.js +5 -1
- package/lib/core/api-client.d.ts +14 -7
- package/lib/core/api-client.js +69 -1
- package/lib/core/bff/config.js +1 -1
- package/lib/core/bff/file-system.js +6 -1
- package/lib/core/bff/hash.js +1 -1
- package/lib/core/bff/hook-directory.js +9 -1
- package/lib/core/bff/lock.js +2 -1
- package/lib/core/bff/types.js +1 -1
- package/lib/core/bff/utils.js +3 -1
- package/lib/core/cross-db-analysis.js +1 -1
- package/lib/core/cross-db-relation.js +1 -1
- package/lib/core/db-resolver.js +2 -1
- package/lib/core/flow-config.js +49 -1
- package/lib/core/instant-api-policy/config.js +7 -1
- package/lib/core/instant-api-policy/endpoints.js +1 -1
- package/lib/core/kb-management-client.d.ts +11 -0
- package/lib/core/kb-management-client.js +4 -1
- package/lib/core/kb-search-client.js +3 -1
- package/lib/core/page/file-system.js +2 -1
- package/lib/core/page/hash.js +1 -1
- package/lib/core/page/lock.js +2 -1
- package/lib/core/page/lr-smart-jsx.js +4 -1
- package/lib/core/page/types.js +1 -1
- package/lib/core/sql-index-auditor.js +14 -1
- package/lib/core/sql-sync/config.js +1 -1
- package/lib/core/sql-sync/file-system.js +3 -1
- package/lib/core/sql-sync/hash.js +1 -1
- package/lib/core/sql-sync/lock.js +2 -1
- package/lib/core/sql-sync/types.js +1 -1
- package/lib/core/sql-sync/utils.js +2 -1
- package/lib/core/sql-validator.js +15 -1
- package/lib/errors.js +3 -1
- package/lib/framework/build-all-flags.js +1 -1
- package/lib/framework/error-output.js +1 -1
- package/lib/framework/explicit-yes.js +1 -1
- package/lib/framework/flags.js +1 -1
- package/lib/framework/help.js +2 -1
- package/lib/framework/index.js +1 -1
- package/lib/framework/output.js +2 -1
- package/lib/framework/response.js +1 -1
- package/lib/framework/runner-alias.js +2 -1
- package/lib/framework/runner.js +9 -1
- package/lib/framework/schema-export.js +1 -1
- package/lib/framework/supported-flags.js +2 -1
- package/lib/framework/types.js +1 -1
- package/lib/generated/build-info.d.ts +4 -4
- package/lib/generated/build-info.js +1 -1
- package/lib/generated/official-routing.js +3 -1
- package/lib/generated/routing-contract.js +1 -1
- package/lib/help.js +1 -1
- package/lib/runtime/confirmation.js +2 -1
- package/lib/runtime/event.js +1 -1
- package/lib/runtime/index.js +4 -1
- package/lib/runtime/queue.js +1 -1
- package/lib/runtime/resolve.js +2 -1
- package/lib/runtime/types.js +1 -1
- package/lib/services/dataset-design/checkpoint.js +2 -1
- package/lib/services/dataset-design/commands.js +14 -1
- package/lib/services/dataset-design/contract.js +8 -1
- package/lib/skills/builtin-skill.js +8 -1
- package/lib/skills/install-updated-skill.d.ts +8 -0
- package/lib/skills/install-updated-skill.js +3 -0
- package/lib/skills/local-skills-installer.d.ts +2 -0
- package/lib/skills/local-skills-installer.js +1 -0
- package/lib/skills/main.js +2 -1
- package/lib/skills/npx-skills-add.d.ts +6 -6
- package/lib/skills/npx-skills-add.js +5 -1
- package/lib/skills/skill-presence.d.ts +1 -30
- package/lib/skills/skill-presence.js +2 -1
- package/lib/telemetry/cli-command-trace.js +2 -1
- package/lib/telemetry/cli-help-trace.js +1 -1
- package/lib/telemetry/ensure-cli-otel-config.js +1 -1
- package/lib/telemetry/register-otel-exit-shutdown.js +1 -1
- package/lib/telemetry/send-cli-trace-log.js +1 -1
- package/lib/types/index.js +1 -1
- package/lib/utils/ai_config.js +3 -1
- package/lib/utils/apply-jq-filter.js +1 -1
- package/lib/utils/cdn-config.js +1 -1
- package/lib/utils/check-sdk-version.js +5 -1
- package/lib/utils/cli-version-check.js +4 -1
- package/lib/utils/cli-version-policy.js +3 -1
- package/lib/utils/config.js +1 -1
- package/lib/utils/entity-with-id.js +1 -1
- package/lib/utils/file-utils.js +1 -1
- package/lib/utils/guides-cdn.js +3 -1
- package/lib/utils/http-client.js +2 -1
- package/lib/utils/is-non-interactive.js +1 -1
- package/lib/utils/logger.js +3 -1
- package/lib/utils/params.js +1 -1
- package/lib/utils/platform.js +1 -1
- package/lib/utils/sleep.js +1 -1
- package/lib/utils/template-replacer.js +5 -1
- package/lib/utils/update-notice.js +3 -1
- package/lib/utils/version.js +1 -1
- package/lib/utils/with-active-cookie.js +1 -1
- package/lib/utils/write-cli-side-channel.js +1 -1
- package/package.json +10 -7
- package/skills/rabetbase/SKILL.md +11 -7
- package/skills/rabetbase/guides/backend-function.md +3 -1
- package/skills/rabetbase/guides/data-api-guidelines.md +1 -1
- package/skills/rabetbase/guides/frontend-development.md +1 -0
- package/skills/rabetbase/guides/metric-development.md +185 -0
- package/skills/rabetbase/references/rabetbase-app-config.md +4 -3
- package/skills/rabetbase/references/rabetbase-cli-skill-install.md +5 -5
- package/skills/rabetbase/references/rabetbase-dataset-design.md +1 -1
- package/skills/rabetbase/references/rabetbase-kb.md +16 -0
- package/skills/rabetbase/references/rabetbase-metric.md +119 -0
- package/skills/rabetbase/references/rabetbase-update.md +7 -5
- package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
- package/skills/rabetbase-dataset-generation/references/workflow.md +1 -1
- package/skills/rabetbase-metrics-generation/SKILL.md +22 -0
- package/skills/rabetbase-metrics-generation/references/verification.md +19 -0
- package/skills/rabetbase-metrics-generation/references/workflow.md +41 -0
- package/skills/rabetbase-metrics-generation/templates/statistics-delivery.md +11 -0
- package/skills/rabetbase-page-generation/SKILL.md +1 -1
- package/skills/rabetbase-page-generation/references/generation.md +1 -1
- package/skills/rabetbase.manifest.json +5 -3
- package/templates/metrics/definition.json +78 -0
- package/templates/metrics/metric-definition.schema.json +136 -0
- package/lib/postinstall.d.ts +0 -3
- package/lib/postinstall.js +0 -1
- package/scripts/postinstall.mjs +0 -24
package/README.md
CHANGED
|
@@ -21,23 +21,34 @@ business Skills, use the Lovrabet runtime CLI (`@lovrabet/lovrabet-cli`).
|
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
24
|
+
Install the CLI, then explicitly install its matching Built-in Skill:
|
|
25
|
+
|
|
24
26
|
```bash
|
|
25
|
-
npm install -g @lovrabet/rabetbase-cli@latest
|
|
27
|
+
npm install -g @lovrabet/rabetbase-cli@latest --ignore-scripts
|
|
28
|
+
rabetbase cli-skill install
|
|
26
29
|
rabetbase --version
|
|
27
|
-
rabetbase
|
|
30
|
+
rabetbase doctor
|
|
28
31
|
```
|
|
29
32
|
|
|
30
|
-
|
|
33
|
+
Use `@beta` for a beta preview, or pin an exact published version for a container
|
|
34
|
+
image. Run the Skill command as the user whose HOME the agent will use.
|
|
35
|
+
The npm package has no install lifecycle hooks. Help, version, and ordinary
|
|
36
|
+
commands do not install Skills automatically.
|
|
31
37
|
|
|
32
|
-
|
|
33
|
-
npm
|
|
34
|
-
|
|
38
|
+
The CLI uses its exact-version local `skills` dependency to install the Built-in
|
|
39
|
+
Skill shipped in the same npm package. Once npm has installed the dependencies,
|
|
40
|
+
Skill installation needs no installer or Skill-content download. No npm script
|
|
41
|
+
approval is needed for this flow.
|
|
35
42
|
|
|
36
|
-
|
|
43
|
+
Treat installation as complete only when the explicit Skill command succeeds
|
|
44
|
+
and `doctor` reports the Built-in Skill as `current`. If the Skill step fails,
|
|
45
|
+
the CLI may already be installed; fix the reported cause and rerun
|
|
46
|
+
`rabetbase cli-skill install`. Do not substitute a remote repository's Skill.
|
|
37
47
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
48
|
+
`rabetbase update` installs the target CLI and invokes that new package's explicit
|
|
49
|
+
Skill installer before reporting success. A failed Skill step returns failure
|
|
50
|
+
without claiming that the CLI package was rolled back. With older updaters,
|
|
51
|
+
finish the transition by running `rabetbase cli-skill install` explicitly.
|
|
41
52
|
|
|
42
53
|
## Update and Verify
|
|
43
54
|
|
|
@@ -185,28 +196,38 @@ The generated project file always contains the two complete final URLs.
|
|
|
185
196
|
|
|
186
197
|
## AI Agent Skill
|
|
187
198
|
|
|
188
|
-
|
|
189
|
-
Rabetbase CLI Built-in Skill
|
|
190
|
-
|
|
199
|
+
After installing the npm package, explicitly install the same-version main
|
|
200
|
+
Rabetbase CLI Built-in Skill with the command below. It uses the package-local
|
|
201
|
+
source and the exact-version local official Skills CLI dependency.
|
|
202
|
+
`rabetbase update` installs the new CLI and invokes its Skill installer; the same
|
|
203
|
+
command also repairs the current installation:
|
|
191
204
|
|
|
192
205
|
```bash
|
|
193
206
|
rabetbase cli-skill install
|
|
194
207
|
```
|
|
195
208
|
|
|
196
|
-
The package also includes the independent `rabetbase-page-generation
|
|
197
|
-
`rabetbase-dataset-generation` Skills. Install each one explicitly from the
|
|
209
|
+
The package also includes the independent `rabetbase-page-generation`,
|
|
210
|
+
`rabetbase-dataset-generation`, and `rabetbase-metrics-generation` Skills. Install each one explicitly from the
|
|
198
211
|
installed CLI package directory:
|
|
199
212
|
|
|
200
213
|
```sh
|
|
201
214
|
npx skills add /path/to/rabetbase-cli/skills/rabetbase-page-generation -g -y
|
|
202
215
|
npx skills add /path/to/rabetbase-cli/skills/rabetbase-dataset-generation -g -y
|
|
216
|
+
npx skills add /path/to/rabetbase-cli/skills/rabetbase-metrics-generation -g -y
|
|
203
217
|
```
|
|
204
218
|
|
|
205
|
-
Replace the paths with the actual package location. `
|
|
206
|
-
`rabetbase cli-skill install`, and `rabetbase doctor` manage only the main
|
|
219
|
+
Replace the paths with the actual package location. `rabetbase cli-skill install`, and `rabetbase doctor` manage only the main
|
|
207
220
|
`rabetbase` Built-in Skill; reinstall independent Skills explicitly after a CLI
|
|
208
221
|
update when needed.
|
|
209
222
|
|
|
223
|
+
The metrics companion handles explicitly authorized development requests and
|
|
224
|
+
accepted report gaps. It reuses existing cloud metrics, verifies each delivery
|
|
225
|
+
stage, and returns references to the original report task. Local source files
|
|
226
|
+
are optional development aids. Operators do not need the developer CLI to ask
|
|
227
|
+
for reports; their environment administrator provisions `lovrabet-report-generation`.
|
|
228
|
+
Verify each companion's installed name, version and references in the intended
|
|
229
|
+
Agent host; a current main Skill does not certify companion installation.
|
|
230
|
+
|
|
210
231
|
Runtime business Skills are installed with the Lovrabet runtime CLI after
|
|
211
232
|
selecting the target runtime app:
|
|
212
233
|
|
|
@@ -314,3 +335,7 @@ rabetbase issue report --title "Page push failed" --description-file ./issue.md
|
|
|
314
335
|
|
|
315
336
|
Preview the redacted content before submitting. On success, the command displays
|
|
316
337
|
`Issue log submitted`.
|
|
338
|
+
|
|
339
|
+
### 指标目录与本地校验
|
|
340
|
+
|
|
341
|
+
`rabetbase metric schema` 读取指标 JSON Schema;`rabetbase metric example` 返回单个自包含定义;`rabetbase metric validate --file <metric.json>` 检查定义、内嵌 JSON contract 及示例;`metric schema --kind contract` 读取 contract 结构。计算继续复用已有 SQL/BFF,运行态 `lovrabet metric exec` 负责调用前后校验。详见 [命令参考](skills/rabetbase/references/rabetbase-metric.md)、[定义结构](templates/metrics/metric-definition.schema.json)、[内置示例](templates/metrics/definition.json) 和 [操作指引](https://qizhiyuntu.feishu.cn/wiki/PY4DwJ2a8iyaf9koETicamgEnAf)。
|
package/lib/api/api-doc.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import path from"node:path";import{fetchDatasetDoc}from"../core/api-client.js";import{logger}from"../utils/logger.js";export{fetchDatasetDoc}from"../core/api-client.js";function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}export async function generateDatasetDocs(datasets,appCode,cookie,outputDir="./docs",onProgress,extraParams){mkdirSync(outputDir,{recursive:true});const results=[];const totalCount=datasets.length;console.log(`\n${totalCount} datasets to generate docs for\n`);for(let i=0;i<datasets.length;i++){const dataset=datasets[i];const currentIndex=i+1;const fileName=dataset.tableName;try{console.log(`[${currentIndex}/${totalCount}] Generating: ${fileName}.md (${dataset.name})`);if(onProgress)onProgress(currentIndex,totalCount,fileName);const markdown=await fetchDatasetDoc({appCode:appCode,cookie:cookie,datasetCode:dataset.datasetCode,datasetId:dataset.id,enableAI:false,extraParams:extraParams})
|
|
2
|
+
;const filePath=path.join(outputDir,`${fileName}.md`);writeFileSync(filePath,markdown,{encoding:"utf8"});console.log(`✓ Generated: ${fileName}.md`);logger.success("api-doc",`Generated docs successfully: ${fileName}`,undefined,{datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:filePath,progress:`${currentIndex}/${totalCount}`});results.push({datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:filePath,success:true});if(currentIndex<totalCount)await delay(5e3)}catch(err){const errorMessage=err instanceof Error?err.message:String(err);console.log(`✗ Failed: ${fileName}.md - ${errorMessage}`);logger.error("api-doc",`Failed to generate docs: ${dataset.datasetCode}`,{datasetCode:dataset.datasetCode,datasetName:dataset.name,error:errorMessage,progress:`${currentIndex}/${totalCount}`});results.push({datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:"",success:false,error:errorMessage});if(currentIndex<totalCount){
|
|
3
|
+
console.log("Waiting 3 seconds...\n");await delay(3e3)}}}return results}
|
package/lib/api/api-group.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import path from"node:path";import{CliErrors}from"../errors.js";export function normalizeApiDir(apiDir,baseDir=process.cwd()){return path.resolve(baseDir,apiDir)}function normalizedApiGroup(value){const normalized=value?.trim();return normalized||undefined}export function resolveApiProfileLayouts(apps,resolveOutputDir,baseDir=process.cwd()){const layouts=apps.map(app=>{const outputDir=resolveOutputDir(app);return{app:app,outputDir:outputDir,normalizedApiDir:normalizeApiDir(outputDir,baseDir),apiGroup:normalizedApiGroup(app.apiGroup)}});const directoriesByGroup=new Map;for(const layout of layouts){if(!layout.apiGroup)continue;const directories=directoriesByGroup.get(layout.apiGroup)??new Set;directories.add(layout.normalizedApiDir);directoriesByGroup.set(layout.apiGroup,directories)}for(const[apiGroup,directories]of directoriesByGroup){if(directories.size>1){
|
|
2
|
+
throw CliErrors.validation(`API group "${apiGroup}" resolves to multiple API directories.`,"Profiles in the same API group must use the same apiDir.")}}const layoutsByDirectory=new Map;for(const layout of layouts){const peers=layoutsByDirectory.get(layout.normalizedApiDir)??[];peers.push(layout);layoutsByDirectory.set(layout.normalizedApiDir,peers)}for(const peers of layoutsByDirectory.values()){const explicitGroups=new Set(peers.flatMap(layout=>layout.apiGroup?[layout.apiGroup]:[]));if(explicitGroups.size===0)continue;if(explicitGroups.size>1||peers.some(layout=>!layout.apiGroup)){const names=peers.map(layout=>layout.app.name).join(", ");throw CliErrors.validation(`API directory "${peers[0].outputDir}" is assigned to incompatible API groups.`,`Profiles sharing one apiDir must use the same explicit apiGroup. Conflicting profiles: ${names}. Use a different apiDir for a separate API.`)}}return layouts}export function getRegistryGroup(layouts,selected){if(selected.apiGroup){
|
|
3
|
+
return layouts.filter(layout=>layout.apiGroup===selected.apiGroup)}const directoryPeers=layouts.filter(layout=>layout.normalizedApiDir===selected.normalizedApiDir);return directoryPeers.length===1?directoryPeers:undefined}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export{fetchModelList}from"../core/api-client.js";
|
|
@@ -1 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import prettier from"prettier";import{existsSync,mkdirSync,writeFileSync,readFileSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";import{TemplateReplacer}from"../utils/template-replacer.js";import{CLI_BIN_NAME}from"../constant/cli.js";import{logger}from"../utils/logger.js";import{isProduction}from"../constant/env.js";import{generateSdkConfigFile}from"../api/generate-sdk-config-file.js";import{MODEL_REGISTRY_FILE_NAME,MODEL_RUNTIME_FILE_NAME,updateModelRegistry}from"../api/model-registry-file.js";import{renderModelRegistryScaffold}from"../api/model-registry-scaffold.js";function fileAction(existed,wrote){if(!wrote)return existed?"preserved":"missing";return existed?"overwritten":"created"}export async function generateApiFile(configArray,filePrefix,appCode,isFromDefaultConfig,env,outputDir,appName,sdkRouting={},options={}){if(!appCode){throw new Error(`Please configure app code first via \`${CLI_BIN_NAME} config set app <value>\``)}
|
|
2
|
+
const isDefaultConfig=isFromDefaultConfig&&!appName;const profileAware=!!options.modelProfile;const effectiveIsDefaultConfig=profileAware||isDefaultConfig;const effectiveName=appName||appCode;const publicConfigName=profileAware||isDefaultConfig?"default":effectiveName;const configNameExpression=profileAware||isDefaultConfig?"CONFIG_NAMES.DEFAULT":JSON.stringify(effectiveName);const needsEnvParam=!isProduction(env);const envPart=needsEnvParam?`, env: ${JSON.stringify(env)}`:"";const clientConfigParam=`{ apiConfigName: ${configNameExpression}${envPart}, ...LOVRABET_SDK_CONFIG }`;const effectiveFilePrefix=profileAware?"":filePrefix;const apiFileName=effectiveFilePrefix?`${effectiveFilePrefix}-api`:"api";const clientFileName=effectiveFilePrefix?`${effectiveFilePrefix}-client`:"client";const normalizedVarPrefix=effectiveFilePrefix&&!/^app-[a-f0-9]+$/i.test(effectiveFilePrefix)?effectiveFilePrefix.replace(/-/g,"_").toUpperCase():"LOVRABET"
|
|
3
|
+
;const varPrefix=/^\d/.test(normalizedVarPrefix)?`APP_${normalizedVarPrefix}`:normalizedVarPrefix;const modelConfigs=configArray.map(item=>({datasetCode:item.datasetCode,tableName:item.tableName,name:item.name||"",alias:item.alias||item.key}));const currentFilePath=fileURLToPath(import.meta.url);const cliRootDir=path.resolve(path.dirname(currentFilePath),"../..");const templateDir=path.join(cliRootDir,"templates/generate-api");const apiTemplatePath=path.join(templateDir,"api.ts.tpl");const clientTemplatePath=path.join(templateDir,"client.ts.tpl");const normalizedOutputDir=outputDir;mkdirSync(normalizedOutputDir,{recursive:true});const generatedSdkRouting=profileAware?{}:sdkRouting;const sdkConfigPath=await generateSdkConfigFile(normalizedOutputDir,generatedSdkRouting,effectiveFilePrefix);const sdkConfigFileName=path.basename(sdkConfigPath,".ts");const apiFilePath=path.join(normalizedOutputDir,`${apiFileName}.ts`)
|
|
4
|
+
;const clientFilePath=path.join(normalizedOutputDir,`${clientFileName}.ts`);const overwriteTypescript=options.overwriteTypescript===true;const apiExisted=existsSync(apiFilePath);const clientExisted=existsSync(clientFilePath);const scaffoldMode=options.scaffoldMode??(overwriteTypescript?"replace":"missing");const writeApi=scaffoldMode==="replace"||scaffoldMode==="missing"&&!apiExisted;const writeClient=scaffoldMode==="replace"||scaffoldMode==="missing"&&!clientExisted;const modelRegistry=options.modelProfile?updateModelRegistry({outputDir:normalizedOutputDir,profileName:options.modelProfile.name,defaultProfile:options.modelProfile.defaultName,appCode:appCode,runtimeDomain:options.modelProfile.runtimeDomain,models:modelConfigs,allowEmptyReplacement:options.allowEmptyModelReplacement===true}):undefined;const modelRuntimePath=modelRegistry?path.join(normalizedOutputDir,MODEL_RUNTIME_FILE_NAME):undefined;const modelRuntimeExisted=modelRuntimePath?existsSync(modelRuntimePath):false
|
|
5
|
+
;const profileScaffold=profileAware&&scaffoldMode!=="none"?await renderModelRegistryScaffold(normalizedOutputDir):undefined;if(modelRuntimePath&&profileScaffold){writeFileSync(modelRuntimePath,profileScaffold.modelRuntime,"utf8")}const exampleModelName=modelConfigs[0]?.alias;if(writeApi){const apiTemplate=profileScaffold?.api??readFileSync(apiTemplatePath,"utf8");const apiContent=profileAware?apiTemplate:TemplateReplacer.replaceApiContent(apiTemplate,appCode,modelConfigs,exampleModelName,apiFileName,configNameExpression,undefined,varPrefix);writeFileSync(apiFilePath,await prettier.format(apiContent,{parser:"typescript"}),{encoding:"utf8"})}if(writeClient){const clientTemplate=profileScaffold?.client??readFileSync(clientTemplatePath,"utf8");const clientContent=profileAware?clientTemplate:TemplateReplacer.replaceApiContent(clientTemplate,appCode,modelConfigs,exampleModelName,apiFileName,configNameExpression,clientConfigParam,varPrefix,sdkConfigFileName)
|
|
6
|
+
;writeFileSync(clientFilePath,await prettier.format(clientContent,{parser:"typescript"}),{encoding:"utf8"})}const modelCount=modelConfigs.length;const files={api:{path:apiFilePath,action:fileAction(apiExisted,writeApi)},client:{path:clientFilePath,action:fileAction(clientExisted,writeClient)},sdkConfig:{path:sdkConfigPath,action:"refreshed"},...modelRegistry?{modelRegistry:{path:modelRegistry.path,action:modelRegistry.existed?"refreshed":"created"},modelRuntime:{path:modelRuntimePath,action:profileScaffold?modelRuntimeExisted?"refreshed":"created":modelRuntimeExisted?"preserved":"missing"}}:{}};const apiUsesRegistry=existsSync(apiFilePath)&&readFileSync(apiFilePath,"utf8").includes(MODEL_REGISTRY_FILE_NAME.replace(".ts",""));const clientUsesRegistry=existsSync(clientFilePath)&&readFileSync(clientFilePath,"utf8").includes("LOVRABET_RUNTIME_DOMAIN");const needsProjectUpgrade=profileAware?!apiUsesRegistry||!clientUsesRegistry||!existsSync(modelRuntimePath):false
|
|
7
|
+
;const needsAgentMerge=profileAware?needsProjectUpgrade:files.api.action==="preserved"||files.client.action==="preserved";logger.success("init-api",needsAgentMerge?`${path.basename(sdkConfigPath)} refreshed; existing TypeScript left unchanged.`:profileAware?"Model facts refreshed.":"API scaffold written.",undefined,{apiFile:apiFilePath,clientFile:clientFilePath,sdkConfig:sdkConfigPath,modelCount:modelCount,configName:publicConfigName,isDefaultConfig:effectiveIsDefaultConfig,needsAgentMerge:needsAgentMerge,needsProjectUpgrade:needsProjectUpgrade,files:files});return{appCode:appCode,modelCount:modelCount,models:modelConfigs,apiFilePath:apiFilePath,clientFilePath:clientFilePath,sdkConfigPath:sdkConfigPath,modelRegistryPath:modelRegistry?.path,modelRuntimePath:modelRuntimePath,modelProfile:options.modelProfile?.name,configName:publicConfigName,isDefaultConfig:effectiveIsDefaultConfig,sdkRouting:generatedSdkRouting,files:files,needsAgentMerge:needsAgentMerge,
|
|
8
|
+
needsProjectUpgrade:needsProjectUpgrade}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import path from"node:path";import prettier from"prettier";export const SDK_CONFIG_FILE_NAME="sdk-config.ts";export function getSdkConfigFileName(filePrefix=""){return filePrefix?`${filePrefix}-sdk-config.ts`:SDK_CONFIG_FILE_NAME}export async function generateSdkConfigFile(outputDir,config={},filePrefix=""){const entries=[];if(config.runtimeDomain){entries.push(`runtimeDomain: ${JSON.stringify(config.runtimeDomain)}`)}const objectBody=entries.length>0?`{\n ${entries.join(",\n ")},\n}`:"{}";const content=`/**\n * Lovrabet SDK runtime routing.\n * Generated by Rabetbase CLI. Do not add credentials to this file.\n */\nexport const LOVRABET_SDK_CONFIG = ${objectBody} as const;\n`;mkdirSync(outputDir,{recursive:true});const filePath=path.join(outputDir,getSdkConfigFileName(filePrefix));writeFileSync(filePath,await prettier.format(content,{parser:"typescript"}),"utf8");return filePath}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
export function parseLegacyApiModels(content){const models=[];const modelRe=/\{\s*datasetCode:\s*"([^"]+)"\s*,\s*tableName:\s*"([^"]+)"\s*,\s*name:\s*"([^"]*?)"\s*,\s*alias:\s*"([^"]+)"\s*,?\s*\}/g;let match;while((match=modelRe.exec(content))!==null){models.push({datasetCode:match[1],tableName:match[2],name:match[3],alias:match[4]})}return models}export function parseLegacyApiAppCode(content){return content.match(/export\s+const\s+[A-Z0-9_]*APP_CODE(?:\s*:\s*string)?\s*=\s*["']([^"']+)["']/)?.[1]}function stripComments(content){return content.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}export function isLegacyGeneratedApiScaffold(content){if(!content.includes("Generated by Rabetbase CLI"))return false;const source=stripComments(content);const imports=[...source.matchAll(/^import[\s\S]*?from\s+["']([^"']+)["'];?$/gm)].map(match=>match[1]);if(imports.length!==1||imports[0]!=="@lovrabet/sdk")return false
|
|
2
|
+
;const variables=[...source.matchAll(/^(?:export\s+)?const\s+([A-Za-z_$][\w$]*)/gm)].map(match=>match[1]);if(variables.length!==2||!variables.some(name=>name.endsWith("APP_CODE"))||!variables.some(name=>name.endsWith("MODELS_CONFIG"))){return false}const topLevelCalls=[...source.matchAll(/^([A-Za-z_$][\w$]*)\s*\(/gm)].map(match=>match[1]);return topLevelCalls.length===1&&topLevelCalls[0]==="registerModels"}export function isLegacyGeneratedClientScaffold(content){if(!content.includes("Generated by Rabetbase CLI"))return false;const source=stripComments(content);const imports=[...source.matchAll(/^(?:import[\s\S]*?from\s+|import\s+)["']([^"']+)["'];?$/gm)].map(match=>match[1]);if(imports.some(moduleName=>moduleName!=="@lovrabet/sdk"&&!/^\.\/(?:[\w-]+-)?(?:api|sdk-config)$/.test(moduleName??""))){return false}const variables=[...source.matchAll(/^(?:export\s+)?const\s+([A-Za-z_$][\w$]*)/gm)].map(match=>match[1]);return variables.length===1&&variables[0]==="lovrabetClient"}
|
|
@@ -1 +1,11 @@
|
|
|
1
|
-
const a6_0x11b664=a6_0x6f0b;(function(_0x44350b,_0x4786a1){const _0x56183b=a6_0x6f0b,_0xb0aec1=_0x44350b();while(!![]){try{const _0x4d04c6=parseInt(_0x56183b(0x16c))/0x1+parseInt(_0x56183b(0x14c))/0x2*(parseInt(_0x56183b(0x13f))/0x3)+parseInt(_0x56183b(0x139))/0x4*(-parseInt(_0x56183b(0x140))/0x5)+parseInt(_0x56183b(0x17e))/0x6+-parseInt(_0x56183b(0x172))/0x7*(-parseInt(_0x56183b(0x16f))/0x8)+-parseInt(_0x56183b(0x170))/0x9*(parseInt(_0x56183b(0x151))/0xa)+parseInt(_0x56183b(0x17c))/0xb;if(_0x4d04c6===_0x4786a1)break;else _0xb0aec1['push'](_0xb0aec1['shift']());}catch(_0x261a17){_0xb0aec1['push'](_0xb0aec1['shift']());}}}(a6_0x2e95,0x1fb65));import{existsSync,mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync}from'node:fs';import a6_0x4ac867 from'node:path';export const MODEL_REGISTRY_FILE_NAME=a6_0x11b664(0x159);export const MODEL_RUNTIME_FILE_NAME='model-runtime.ts';export const MODEL_REGISTRY_VERSION_MARKER=a6_0x11b664(0x14b);const LEGACY_MODEL_REGISTRY_V2_PROTOCOL=a6_0x11b664(0x154),REGISTRY_START=a6_0x11b664(0x14a),REGISTRY_END=a6_0x11b664(0x156);function emptyRegistry(_0x48e728){return{'defaultProfile':_0x48e728,'profiles':{},'models':[]};}function extractRegistryJson(_0x359a92){const _0x5332b7=a6_0x11b664,_0x59c401=_0x359a92[_0x5332b7(0x13e)](REGISTRY_START),_0x238da0=_0x359a92[_0x5332b7(0x13e)](REGISTRY_END);if(_0x59c401<0x0||_0x238da0<=_0x59c401)return undefined;return _0x359a92[_0x5332b7(0x13d)](_0x59c401+REGISTRY_START['length'],_0x238da0)[_0x5332b7(0x173)]()[_0x5332b7(0x141)](/\s+as const satisfies LovrabetModelRegistry;?$/,'')[_0x5332b7(0x141)](/;$/,'');}function migrateLegacyRegistry(_0x59a99c){const _0x329e16=a6_0x11b664,_0x3172a9=emptyRegistry(_0x59a99c[_0x329e16(0x138)]);for(const [_0x13dcd3,_0xc6e00f]of Object[_0x329e16(0x181)](_0x59a99c['profiles'])){_0x3172a9['profiles'][_0x13dcd3]={'appCode':_0xc6e00f['appCode'],'runtimeDomain':_0xc6e00f['runtimeDomain']},mergeProfileModels(_0x3172a9,_0x13dcd3,_0xc6e00f[_0x329e16(0x14f)]);}return _0x3172a9;}function generatedObjectLiteralToJson(_0x2f65ee){const _0x41ca9f=a6_0x11b664;let _0x4599ba='',_0x379eea,_0x5d558b=![],_0x3d59ba;for(let _0x3c4308=0x0;_0x3c4308<_0x2f65ee['length'];_0x3c4308++){const _0x3ce2fc=_0x2f65ee[_0x3c4308];if(_0x379eea){_0x4599ba+=_0x3ce2fc;if(_0x5d558b)_0x5d558b=![];else{if(_0x3ce2fc==='\x5c')_0x5d558b=!![];else{if(_0x3ce2fc===_0x379eea)_0x379eea=undefined;}}continue;}if(_0x3ce2fc==='\x22'){_0x379eea=_0x3ce2fc,_0x4599ba+=_0x3ce2fc,_0x3d59ba='value';continue;}if(_0x3ce2fc===','){let _0x274ba3=_0x3c4308+0x1;while(/\s/[_0x41ca9f(0x15b)](_0x2f65ee[_0x274ba3]??''))_0x274ba3++;if(_0x2f65ee[_0x274ba3]==='}'||_0x2f65ee[_0x274ba3]===']')continue;_0x4599ba+=_0x3ce2fc,_0x3d59ba=',';continue;}if(_0x3ce2fc==='{'||_0x3ce2fc==='['){_0x4599ba+=_0x3ce2fc,_0x3d59ba=_0x3ce2fc;continue;}if(_0x3ce2fc==='}'||_0x3ce2fc===']'){_0x4599ba+=_0x3ce2fc,_0x3d59ba=_0x3ce2fc;continue;}if((_0x3d59ba==='{'||_0x3d59ba===',')&&/[A-Za-z_$]/[_0x41ca9f(0x15b)](_0x3ce2fc)){let _0x45ce5d=_0x3c4308+0x1;while(/[A-Za-z0-9_$]/[_0x41ca9f(0x15b)](_0x2f65ee[_0x45ce5d]??''))_0x45ce5d++;let _0x4accf3=_0x45ce5d;while(/\s/[_0x41ca9f(0x15b)](_0x2f65ee[_0x4accf3]??''))_0x4accf3++;if(_0x2f65ee[_0x4accf3]===':'){_0x4599ba+=JSON[_0x41ca9f(0x175)](_0x2f65ee['slice'](_0x3c4308,_0x45ce5d)),_0x3c4308=_0x45ce5d-0x1,_0x3d59ba='key';continue;}}_0x4599ba+=_0x3ce2fc;if(!/\s/['test'](_0x3ce2fc)&&_0x3ce2fc!==':')_0x3d59ba=_0x41ca9f(0x152);}return _0x4599ba;}function parseGeneratedRegistryJson(_0x1d84cd){const _0x45a7d4=a6_0x11b664;try{return JSON[_0x45a7d4(0x13a)](_0x1d84cd);}catch{return JSON[_0x45a7d4(0x13a)](generatedObjectLiteralToJson(_0x1d84cd));}}function normalizeModelEntries(_0x24cb5c,_0x375c76){const _0xa972bf=a6_0x11b664,_0x21a9eb=Object['keys'](_0x24cb5c),_0x2771ea=[];for(const _0x398ad3 of _0x375c76){if(!_0x398ad3||typeof _0x398ad3!==_0xa972bf(0x17a)||Array['isArray'](_0x398ad3))return undefined;const _0x429ef6=_0x398ad3;if(typeof _0x429ef6[_0xa972bf(0x16e)]!==_0xa972bf(0x143)||typeof _0x429ef6[_0xa972bf(0x166)]!=='string'||typeof _0x429ef6[_0xa972bf(0x15f)]!==_0xa972bf(0x143))return undefined;let _0x580e1c;if(typeof _0x429ef6['datasetCode']===_0xa972bf(0x143)&&_0x429ef6[_0xa972bf(0x174)]===undefined)_0x580e1c=Object[_0xa972bf(0x168)](_0x21a9eb[_0xa972bf(0x161)](_0x15e954=>[_0x15e954,_0x429ef6[_0xa972bf(0x13b)]]));else{if(_0x429ef6[_0xa972bf(0x13b)]===undefined&&_0x429ef6[_0xa972bf(0x174)]&&typeof _0x429ef6['datasetCodes']===_0xa972bf(0x17a)&&!Array[_0xa972bf(0x15e)](_0x429ef6[_0xa972bf(0x174)])&&Object['values'](_0x429ef6[_0xa972bf(0x174)])[_0xa972bf(0x15a)](_0x241892=>typeof _0x241892===_0xa972bf(0x143)))_0x580e1c={..._0x429ef6[_0xa972bf(0x174)]};else return undefined;}_0x2771ea['push']({'alias':_0x429ef6[_0xa972bf(0x16e)],'tableName':_0x429ef6[_0xa972bf(0x166)],'name':_0x429ef6['name'],'datasetCodes':_0x580e1c});}return _0x2771ea;}export function parseModelRegistry(_0x588ae0){const _0x538bc0=a6_0x11b664,_0x3f360b=extractRegistryJson(_0x588ae0);if(!_0x3f360b)return undefined;try{const _0x9d3438=parseGeneratedRegistryJson(_0x3f360b);if(typeof _0x9d3438[_0x538bc0(0x138)]!==_0x538bc0(0x143)||!_0x9d3438[_0x538bc0(0x178)]||typeof _0x9d3438['profiles']!==_0x538bc0(0x17a))return undefined;if(_0x9d3438['protocol']===_0x538bc0(0x155))return migrateLegacyRegistry(_0x9d3438);if(!(_0x9d3438[_0x538bc0(0x160)]===LEGACY_MODEL_REGISTRY_V2_PROTOCOL||_0x9d3438[_0x538bc0(0x160)]===undefined&&_0x588ae0[_0x538bc0(0x171)](MODEL_REGISTRY_VERSION_MARKER))||!Array['isArray'](_0x9d3438['models']))return undefined;const _0x58ecc5=_0x9d3438[_0x538bc0(0x178)],_0x5c221d=normalizeModelEntries(_0x58ecc5,_0x9d3438[_0x538bc0(0x14f)]);if(!_0x5c221d)return undefined;return{'defaultProfile':_0x9d3438[_0x538bc0(0x138)],'profiles':_0x58ecc5,'models':_0x5c221d};}catch{return undefined;}}function a6_0x6f0b(_0x5b2029,_0x3c4a82){_0x5b2029=_0x5b2029-0x138;const _0x2e9511=a6_0x2e95();let _0x6f0b7b=_0x2e9511[_0x5b2029];return _0x6f0b7b;}export function readModelRegistry(_0x9a5cea){const _0x2021ff=a6_0x11b664;if(!existsSync(_0x9a5cea))return undefined;try{return parseModelRegistry(readFileSync(_0x9a5cea,_0x2021ff(0x169)));}catch{return undefined;}}function registrySource(_0x3d20d6){const _0x1d32cc=a6_0x11b664,_0xb14923=Object['keys'](_0x3d20d6[_0x1d32cc(0x178)]),_0x5de70c=_0x3d20d6[_0x1d32cc(0x14f)][_0x1d32cc(0x161)](_0x3c7546=>{const _0x17d664=_0x1d32cc,_0x296ffd=_0xb14923[_0x17d664(0x161)](_0x2965e2=>_0x3c7546['datasetCodes'][_0x2965e2]),_0x5b7931=_0x296ffd[0x0],_0x4532b9=_0x5b7931!==undefined&&_0x296ffd['every'](_0x46c0e3=>_0x46c0e3===_0x5b7931),_0x8cc5d7={'alias':_0x3c7546[_0x17d664(0x16e)],'tableName':_0x3c7546[_0x17d664(0x166)],'name':_0x3c7546['name']};return _0x4532b9?{..._0x8cc5d7,'datasetCode':_0x5b7931}:{..._0x8cc5d7,'datasetCodes':_0x3c7546[_0x17d664(0x174)]};}),_0x155af3=JSON[_0x1d32cc(0x175)]({'defaultProfile':_0x3d20d6['defaultProfile'],'profiles':_0x3d20d6[_0x1d32cc(0x178)],'models':_0x5de70c},null,0x2)['split']('\x0a')[_0x1d32cc(0x161)](_0x4cc7d5=>'\x20\x20'+_0x4cc7d5)[_0x1d32cc(0x153)]('\x0a');return _0x1d32cc(0x148)+MODEL_REGISTRY_VERSION_MARKER+_0x1d32cc(0x177)+REGISTRY_START+'\x0a'+_0x155af3+_0x1d32cc(0x179)+REGISTRY_END+'\x0a';}function mergeProfileModels(_0x526391,_0x4c6de8,_0x543df9){const _0x4ca864=a6_0x11b664,_0x59c201=_0x543df9[_0x4ca864(0x161)](_0x12d2c4=>({..._0x12d2c4,'alias':_0x12d2c4[_0x4ca864(0x16e)]||_0x12d2c4[_0x4ca864(0x166)]})),_0x430596=new Map(),_0x1df36a=new Map();for(const _0x45de62 of _0x59c201){const _0x41a7d2=_0x430596['get'](_0x45de62[_0x4ca864(0x16e)]);if(_0x41a7d2&&_0x41a7d2!==_0x45de62[_0x4ca864(0x166)])throw new Error(_0x4ca864(0x158)+_0x45de62[_0x4ca864(0x16e)]+_0x4ca864(0x15c)+_0x41a7d2+'\x22\x20and\x20\x22'+_0x45de62[_0x4ca864(0x166)]+'\x22\x20in\x20profile\x20\x22'+_0x4c6de8+'\x22.');const _0x5cf703=_0x1df36a[_0x4ca864(0x176)](_0x45de62[_0x4ca864(0x166)]);if(_0x5cf703&&_0x5cf703!==_0x45de62['alias'])throw new Error('Table\x20\x22'+_0x45de62[_0x4ca864(0x166)]+_0x4ca864(0x13c)+_0x5cf703+'\x22\x20and\x20\x22'+_0x45de62[_0x4ca864(0x16e)]+_0x4ca864(0x150)+_0x4c6de8+'\x22.');_0x430596['set'](_0x45de62[_0x4ca864(0x16e)],_0x45de62[_0x4ca864(0x166)]),_0x1df36a[_0x4ca864(0x14d)](_0x45de62[_0x4ca864(0x166)],_0x45de62[_0x4ca864(0x16e)]);const _0x5f5448=_0x526391[_0x4ca864(0x14f)][_0x4ca864(0x16a)](_0x55045e=>_0x55045e[_0x4ca864(0x16e)]===_0x45de62['alias']);if(_0x5f5448&&_0x5f5448[_0x4ca864(0x166)]!==_0x45de62[_0x4ca864(0x166)])throw new Error(_0x4ca864(0x158)+_0x45de62[_0x4ca864(0x16e)]+_0x4ca864(0x14e)+_0x5f5448[_0x4ca864(0x166)]+_0x4ca864(0x157)+_0x45de62[_0x4ca864(0x166)]+_0x4ca864(0x150)+_0x4c6de8+'\x22.');const _0x2f6c50=_0x526391[_0x4ca864(0x14f)][_0x4ca864(0x16a)](_0x2d6cd8=>_0x2d6cd8['tableName']===_0x45de62[_0x4ca864(0x166)]);if(_0x2f6c50&&_0x2f6c50[_0x4ca864(0x16e)]!==_0x45de62['alias'])throw new Error(_0x4ca864(0x165)+_0x45de62[_0x4ca864(0x166)]+_0x4ca864(0x146)+_0x2f6c50[_0x4ca864(0x16e)]+'\x22\x20in\x20the\x20registry\x20but\x20\x22'+_0x45de62[_0x4ca864(0x16e)]+_0x4ca864(0x150)+_0x4c6de8+'\x22.');}for(const _0x5a7783 of _0x526391[_0x4ca864(0x14f)]){delete _0x5a7783[_0x4ca864(0x174)][_0x4c6de8];}for(const _0xe1ee46 of _0x59c201){let _0x4f40f9=_0x526391['models'][_0x4ca864(0x16a)](_0x7eb432=>_0x7eb432[_0x4ca864(0x16e)]===_0xe1ee46[_0x4ca864(0x16e)]);!_0x4f40f9&&(_0x4f40f9={'alias':_0xe1ee46[_0x4ca864(0x16e)],'tableName':_0xe1ee46[_0x4ca864(0x166)],'name':_0xe1ee46[_0x4ca864(0x15f)],'datasetCodes':{}},_0x526391['models'][_0x4ca864(0x180)](_0x4f40f9)),(_0x4c6de8===_0x526391[_0x4ca864(0x138)]||!_0x4f40f9['datasetCodes'][_0x526391[_0x4ca864(0x138)]])&&(_0x4f40f9['alias']=_0xe1ee46['alias'],_0x4f40f9[_0x4ca864(0x166)]=_0xe1ee46[_0x4ca864(0x166)],_0x4f40f9['name']=_0xe1ee46[_0x4ca864(0x15f)]),_0x4f40f9[_0x4ca864(0x174)][_0x4c6de8]=_0xe1ee46[_0x4ca864(0x13b)];}_0x526391[_0x4ca864(0x14f)]=_0x526391[_0x4ca864(0x14f)]['filter'](_0x309c01=>Object[_0x4ca864(0x167)](_0x309c01[_0x4ca864(0x174)])[_0x4ca864(0x149)]>0x0);}function removeUnboundProfiles(_0x9f30a0){const _0x4cfc1b=a6_0x11b664,_0x1d82fb=Object[_0x4cfc1b(0x181)](_0x9f30a0[_0x4cfc1b(0x178)])[_0x4cfc1b(0x163)](([,_0x1afa8f])=>_0x1afa8f[_0x4cfc1b(0x142)]===_0x4cfc1b(0x16d))[_0x4cfc1b(0x161)](([_0x1b70c7])=>_0x1b70c7);if(_0x1d82fb[_0x4cfc1b(0x149)]===0x0)return;for(const _0x479dbd of _0x1d82fb){delete _0x9f30a0[_0x4cfc1b(0x178)][_0x479dbd];for(const _0x1d0024 of _0x9f30a0['models']){delete _0x1d0024[_0x4cfc1b(0x174)][_0x479dbd];}}_0x9f30a0['models']=_0x9f30a0[_0x4cfc1b(0x14f)][_0x4cfc1b(0x163)](_0x2a6b6d=>Object[_0x4cfc1b(0x167)](_0x2a6b6d['datasetCodes'])[_0x4cfc1b(0x149)]>0x0);}function a6_0x2e95(){const _0x30ed1c=['\x22\x20maps\x20to\x20alias\x20\x22','pid','/**\x0a\x20*\x20Dataset\x20model\x20facts\x20generated\x20by\x20Rabetbase\x20CLI.\x0a\x20*\x0a\x20*\x20This\x20file\x20is\x20safe\x20to\x20commit.\x20Do\x20not\x20edit\x20it\x20manually\x20and\x20never\x20add\x20credentials.\x0a\x20*/\x0a\x0aexport\x20interface\x20LovrabetModelProfile\x20{\x0a\x20\x20appCode:\x20string;\x0a\x20\x20runtimeDomain:\x20string;\x0a}\x0a\x0aexport\x20interface\x20LovrabetModelEntryMetadata\x20{\x0a\x20\x20alias:\x20string;\x0a\x20\x20tableName:\x20string;\x0a\x20\x20name:\x20string;\x0a}\x0a\x0aexport\x20type\x20LovrabetModelEntry\x20=\x20LovrabetModelEntryMetadata\x20&\x20(\x0a\x20\x20|\x20{\x20datasetCode:\x20string;\x20datasetCodes?:\x20never\x20}\x0a\x20\x20|\x20{\x20datasetCode?:\x20never;\x20datasetCodes:\x20Record<string,\x20string>\x20}\x0a);\x0a\x0aexport\x20interface\x20LovrabetModelRegistry\x20{\x0a\x20\x20defaultProfile:\x20string;\x0a\x20\x20profiles:\x20Record<string,\x20LovrabetModelProfile>;\x0a\x20\x20models:\x20LovrabetModelEntry[];\x0a}\x0a\x0a','length','/*\x20rabetbase-model-registry:start\x20*/','/*\x20rabetbase-model-registry:v2\x20*/','2360IQWOcU','set','\x22\x20maps\x20to\x20table\x20\x22','models','\x22\x20in\x20profile\x20\x22','230RqJceK','value','join','lovrabet-model-registry/v2','lovrabet-model-registry/v1','/*\x20rabetbase-model-registry:end\x20*/','\x22\x20in\x20the\x20registry\x20but\x20\x22','Model\x20alias\x20\x22','models.generated.ts','every','test','\x22\x20maps\x20to\x20both\x20\x22','runtimeDomain','isArray','name','protocol','map','\x22\x20with\x20an\x20empty\x20result.\x20','filter','flatMap','Table\x20\x22','tableName','keys','fromEntries','utf8','find','profileName','122332UVZnpA','NOT-SET','alias','80xnUOkJ','56232NwUWBJ','includes','23653oCqNJz','trim','datasetCodes','stringify','get','\x0aexport\x20const\x20LOVRABET_MODEL_REGISTRY\x20=\x0a\x20\x20','profiles','\x20as\x20const\x20satisfies\x20LovrabetModelRegistry;\x0a','object','outputDir','498201TMEcxO','\x20model(s)\x20in\x20profile\x20\x22','746022hnyebK','allowEmptyReplacement','push','entries','defaultProfile','110716LKzrQO','parse','datasetCode','\x22\x20maps\x20to\x20both\x20aliases\x20\x22','slice','indexOf','360Njcosp','35fVLyFh','replace','appCode','string','Refusing\x20to\x20replace\x20','\x20is\x20not\x20a\x20valid\x20Rabetbase\x20generated\x20file.\x20Move\x20or\x20repair\x20it\x20before\x20pulling\x20models\x20again.'];a6_0x2e95=function(){return _0x30ed1c;};return a6_0x2e95();}export function getProfileModels(_0x21425a,_0x1b4ff1){const _0x517fbb=a6_0x11b664;return _0x21425a['models'][_0x517fbb(0x164)](_0x211234=>{const _0x15f15a=_0x517fbb,_0x2019cf=_0x211234[_0x15f15a(0x174)][_0x1b4ff1];return _0x2019cf?[{'datasetCode':_0x2019cf,'tableName':_0x211234[_0x15f15a(0x166)],'name':_0x211234['name'],'alias':_0x211234[_0x15f15a(0x16e)]}]:[];});}export function updateModelRegistry(_0x5690ee){const _0x591b91=a6_0x11b664,_0x2bb649=a6_0x4ac867[_0x591b91(0x153)](_0x5690ee[_0x591b91(0x17b)],MODEL_REGISTRY_FILE_NAME),_0x3082a9=existsSync(_0x2bb649),_0x34d0d3=readModelRegistry(_0x2bb649);if(_0x3082a9&&!_0x34d0d3)throw new Error(MODEL_REGISTRY_FILE_NAME+_0x591b91(0x145));const _0x33714f=_0x34d0d3??emptyRegistry(_0x5690ee[_0x591b91(0x138)]);if(_0x5690ee[_0x591b91(0x142)]!==_0x591b91(0x16d))removeUnboundProfiles(_0x33714f);const _0x4f96b2=_0x34d0d3?getProfileModels(_0x34d0d3,_0x5690ee[_0x591b91(0x16b)])[_0x591b91(0x149)]:0x0;if(_0x4f96b2>0x0&&_0x5690ee[_0x591b91(0x14f)][_0x591b91(0x149)]===0x0&&!_0x5690ee[_0x591b91(0x17f)])throw new Error(_0x591b91(0x144)+_0x4f96b2+_0x591b91(0x17d)+_0x5690ee[_0x591b91(0x16b)]+_0x591b91(0x162)+'Verify\x20the\x20selected\x20app\x20and\x20login,\x20or\x20rerun\x20with\x20--force\x20--yes\x20if\x20the\x20profile\x20is\x20intentionally\x20empty.');_0x33714f[_0x591b91(0x138)]=_0x5690ee[_0x591b91(0x138)],_0x33714f[_0x591b91(0x178)][_0x5690ee[_0x591b91(0x16b)]]={'appCode':_0x5690ee['appCode'],'runtimeDomain':_0x5690ee[_0x591b91(0x15d)]},mergeProfileModels(_0x33714f,_0x5690ee['profileName'],_0x5690ee[_0x591b91(0x14f)]),mkdirSync(_0x5690ee[_0x591b91(0x17b)],{'recursive':!![]});const _0x37f74f=_0x2bb649+'.'+process[_0x591b91(0x147)]+'.'+Date['now']()+'.tmp';try{writeFileSync(_0x37f74f,registrySource(_0x33714f),{'encoding':_0x591b91(0x169),'mode':0x1a4}),renameSync(_0x37f74f,_0x2bb649);}catch(_0x1b6193){try{unlinkSync(_0x37f74f);}catch{}throw _0x1b6193;}return{'path':_0x2bb649,'registry':_0x33714f,'existed':_0x3082a9};}
|
|
1
|
+
import{existsSync,mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import path from"node:path";export const MODEL_REGISTRY_FILE_NAME="models.generated.ts";export const MODEL_RUNTIME_FILE_NAME="model-runtime.ts";export const MODEL_REGISTRY_VERSION_MARKER="/* rabetbase-model-registry:v2 */";const LEGACY_MODEL_REGISTRY_V2_PROTOCOL="lovrabet-model-registry/v2";const REGISTRY_START="/* rabetbase-model-registry:start */";const REGISTRY_END="/* rabetbase-model-registry:end */";function emptyRegistry(defaultProfile){return{defaultProfile:defaultProfile,profiles:{},models:[]}}function extractRegistryJson(content){const start=content.indexOf(REGISTRY_START);const end=content.indexOf(REGISTRY_END);if(start<0||end<=start)return undefined;return content.slice(start+REGISTRY_START.length,end).trim().replace(/\s+as const satisfies LovrabetModelRegistry;?$/,"").replace(/;$/,"")}function migrateLegacyRegistry(legacy){const registry=emptyRegistry(legacy.defaultProfile)
|
|
2
|
+
;for(const[profileName,profile]of Object.entries(legacy.profiles)){registry.profiles[profileName]={appCode:profile.appCode,runtimeDomain:profile.runtimeDomain};mergeProfileModels(registry,profileName,profile.models)}return registry}function generatedObjectLiteralToJson(source){let result="";let quote;let escaped=false;let previousToken;for(let index=0;index<source.length;index++){const char=source[index];if(quote){result+=char;if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char===quote)quote=undefined;continue}if(char==='"'){quote=char;result+=char;previousToken="value";continue}if(char===","){let cursor=index+1;while(/\s/.test(source[cursor]??""))cursor++;if(source[cursor]==="}"||source[cursor]==="]")continue;result+=char;previousToken=",";continue}if(char==="{"||char==="["){result+=char;previousToken=char;continue}if(char==="}"||char==="]"){result+=char;previousToken=char;continue}if((previousToken==="{"||previousToken===",")&&/[A-Za-z_$]/.test(char)){
|
|
3
|
+
let cursor=index+1;while(/[A-Za-z0-9_$]/.test(source[cursor]??""))cursor++;let colon=cursor;while(/\s/.test(source[colon]??""))colon++;if(source[colon]===":"){result+=JSON.stringify(source.slice(index,cursor));index=cursor-1;previousToken="key";continue}}result+=char;if(!/\s/.test(char)&&char!==":")previousToken="value"}return result}function parseGeneratedRegistryJson(json){try{return JSON.parse(json)}catch{return JSON.parse(generatedObjectLiteralToJson(json))}}function normalizeModelEntries(profiles,models){const profileNames=Object.keys(profiles);const normalized=[];for(const value of models){if(!value||typeof value!=="object"||Array.isArray(value))return undefined;const entry=value;if(typeof entry.alias!=="string"||typeof entry.tableName!=="string"||typeof entry.name!=="string"){return undefined}let datasetCodes;if(typeof entry.datasetCode==="string"&&entry.datasetCodes===undefined){datasetCodes=Object.fromEntries(profileNames.map(profileName=>[profileName,entry.datasetCode]))
|
|
4
|
+
}else if(entry.datasetCode===undefined&&entry.datasetCodes&&typeof entry.datasetCodes==="object"&&!Array.isArray(entry.datasetCodes)&&Object.values(entry.datasetCodes).every(code=>typeof code==="string")){datasetCodes={...entry.datasetCodes}}else{return undefined}normalized.push({alias:entry.alias,tableName:entry.tableName,name:entry.name,datasetCodes:datasetCodes})}return normalized}export function parseModelRegistry(content){const json=extractRegistryJson(content);if(!json)return undefined;try{const parsed=parseGeneratedRegistryJson(json);if(typeof parsed.defaultProfile!=="string"||!parsed.profiles||typeof parsed.profiles!=="object"){return undefined}if(parsed.protocol==="lovrabet-model-registry/v1"){return migrateLegacyRegistry(parsed)}if(!(parsed.protocol===LEGACY_MODEL_REGISTRY_V2_PROTOCOL||parsed.protocol===undefined&&content.includes(MODEL_REGISTRY_VERSION_MARKER))||!Array.isArray(parsed.models)){return undefined}const profiles=parsed.profiles
|
|
5
|
+
;const models=normalizeModelEntries(profiles,parsed.models);if(!models)return undefined;return{defaultProfile:parsed.defaultProfile,profiles:profiles,models:models}}catch{return undefined}}export function readModelRegistry(filePath){if(!existsSync(filePath))return undefined;try{return parseModelRegistry(readFileSync(filePath,"utf8"))}catch{return undefined}}function registrySource(registry){const profileNames=Object.keys(registry.profiles);const persistedModels=registry.models.map(model=>{const codes=profileNames.map(profileName=>model.datasetCodes[profileName]);const commonDatasetCode=codes[0];const isCommon=commonDatasetCode!==undefined&&codes.every(code=>code===commonDatasetCode);const metadata={alias:model.alias,tableName:model.tableName,name:model.name};return isCommon?{...metadata,datasetCode:commonDatasetCode}:{...metadata,datasetCodes:model.datasetCodes}});const serialized=JSON.stringify({defaultProfile:registry.defaultProfile,profiles:registry.profiles,models:persistedModels
|
|
6
|
+
},null,2).split("\n").map(line=>` ${line}`).join("\n");return`/**\n * Dataset model facts generated by Rabetbase CLI.\n *\n * This file is safe to commit. Do not edit it manually and never add credentials.\n */\n\nexport interface LovrabetModelProfile {\n appCode: string;\n runtimeDomain: string;\n}\n\nexport interface LovrabetModelEntryMetadata {\n alias: string;\n tableName: string;\n name: string;\n}\n\nexport type LovrabetModelEntry = LovrabetModelEntryMetadata & (\n | { datasetCode: string; datasetCodes?: never }\n | { datasetCode?: never; datasetCodes: Record<string, string> }\n);\n\nexport interface LovrabetModelRegistry {\n defaultProfile: string;\n profiles: Record<string, LovrabetModelProfile>;\n models: LovrabetModelEntry[];\n}\n\n${MODEL_REGISTRY_VERSION_MARKER}\nexport const LOVRABET_MODEL_REGISTRY =\n ${REGISTRY_START}\n${serialized} as const satisfies LovrabetModelRegistry;\n${REGISTRY_END}\n`}function mergeProfileModels(registry,profileName,incomingModels){
|
|
7
|
+
const normalizedIncoming=incomingModels.map(incoming=>({...incoming,alias:incoming.alias||incoming.tableName}));const incomingAliases=new Map;const incomingTables=new Map;for(const incoming of normalizedIncoming){const aliasTable=incomingAliases.get(incoming.alias);if(aliasTable&&aliasTable!==incoming.tableName){throw new Error(`Model alias "${incoming.alias}" maps to both "${aliasTable}" and "${incoming.tableName}" in profile "${profileName}".`)}const tableAlias=incomingTables.get(incoming.tableName);if(tableAlias&&tableAlias!==incoming.alias){throw new Error(`Table "${incoming.tableName}" maps to both aliases "${tableAlias}" and "${incoming.alias}" in profile "${profileName}".`)}incomingAliases.set(incoming.alias,incoming.tableName);incomingTables.set(incoming.tableName,incoming.alias);const aliasEntry=registry.models.find(model=>model.alias===incoming.alias);if(aliasEntry&&aliasEntry.tableName!==incoming.tableName){
|
|
8
|
+
throw new Error(`Model alias "${incoming.alias}" maps to table "${aliasEntry.tableName}" in the registry but "${incoming.tableName}" in profile "${profileName}".`)}const tableEntry=registry.models.find(model=>model.tableName===incoming.tableName);if(tableEntry&&tableEntry.alias!==incoming.alias){throw new Error(`Table "${incoming.tableName}" maps to alias "${tableEntry.alias}" in the registry but "${incoming.alias}" in profile "${profileName}".`)}}for(const model of registry.models){delete model.datasetCodes[profileName]}for(const incoming of normalizedIncoming){let entry=registry.models.find(model=>model.alias===incoming.alias);if(!entry){entry={alias:incoming.alias,tableName:incoming.tableName,name:incoming.name,datasetCodes:{}};registry.models.push(entry)}if(profileName===registry.defaultProfile||!entry.datasetCodes[registry.defaultProfile]){entry.alias=incoming.alias;entry.tableName=incoming.tableName;entry.name=incoming.name}entry.datasetCodes[profileName]=incoming.datasetCode}
|
|
9
|
+
registry.models=registry.models.filter(model=>Object.keys(model.datasetCodes).length>0)}function removeUnboundProfiles(registry){const unboundProfileNames=Object.entries(registry.profiles).filter(([,profile])=>profile.appCode==="NOT-SET").map(([profileName])=>profileName);if(unboundProfileNames.length===0)return;for(const profileName of unboundProfileNames){delete registry.profiles[profileName];for(const model of registry.models){delete model.datasetCodes[profileName]}}registry.models=registry.models.filter(model=>Object.keys(model.datasetCodes).length>0)}export function getProfileModels(registry,profileName){return registry.models.flatMap(model=>{const datasetCode=model.datasetCodes[profileName];return datasetCode?[{datasetCode:datasetCode,tableName:model.tableName,name:model.name,alias:model.alias}]:[]})}export function updateModelRegistry(options){const filePath=path.join(options.outputDir,MODEL_REGISTRY_FILE_NAME);const existed=existsSync(filePath)
|
|
10
|
+
;const existing=readModelRegistry(filePath);if(existed&&!existing){throw new Error(`${MODEL_REGISTRY_FILE_NAME} is not a valid Rabetbase generated file. Move or repair it before pulling models again.`)}const registry=existing??emptyRegistry(options.defaultProfile);if(options.appCode!=="NOT-SET")removeUnboundProfiles(registry);const existingProfileModelCount=existing?getProfileModels(existing,options.profileName).length:0;if(existingProfileModelCount>0&&options.models.length===0&&!options.allowEmptyReplacement){throw new Error(`Refusing to replace ${existingProfileModelCount} model(s) in profile "${options.profileName}" with an empty result. `+"Verify the selected app and login, or rerun with --force --yes if the profile is intentionally empty.")}registry.defaultProfile=options.defaultProfile;registry.profiles[options.profileName]={appCode:options.appCode,runtimeDomain:options.runtimeDomain};mergeProfileModels(registry,options.profileName,options.models);mkdirSync(options.outputDir,{
|
|
11
|
+
recursive:true});const tempPath=`${filePath}.${process.pid}.${Date.now()}.tmp`;try{writeFileSync(tempPath,registrySource(registry),{encoding:"utf8",mode:420});renameSync(tempPath,filePath)}catch(error){try{unlinkSync(tempPath)}catch{}throw error}return{path:filePath,registry:registry,existed:existed}}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";import prettier from"prettier";import{PROJECT_DOMAIN_ROUTING_FILE_NAME}from"../config/project-domain-routing.js";function relativeImport(fromDir,targetPath){let value=path.relative(fromDir,targetPath).replace(/\\/g,"/");if(!value.startsWith("."))value=`./${value}`;return value}export async function renderModelRegistryScaffold(outputDir,projectRoot=process.cwd()){const currentFilePath=fileURLToPath(import.meta.url);const templateDir=path.resolve(path.dirname(currentFilePath),"../../templates/generate-api");const routingImport=relativeImport(path.resolve(outputDir),path.resolve(projectRoot,PROJECT_DOMAIN_ROUTING_FILE_NAME));const apiTemplate=readFileSync(path.join(templateDir,"profile-api.ts.tpl"),"utf8").replace("{ProjectRoutingImport}",routingImport);const[api,client,modelRuntime]=await Promise.all([prettier.format(apiTemplate,{parser:"typescript"
|
|
2
|
+
}),prettier.format(readFileSync(path.join(templateDir,"profile-client.ts.tpl"),"utf8"),{parser:"typescript"}),prettier.format(readFileSync(path.join(templateDir,"model-runtime.ts.tpl"),"utf8"),{parser:"typescript"})]);return{api:api,client:client,modelRuntime:modelRuntime}}
|
package/lib/api/model-source.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync}from"node:fs";import path from"node:path";import{readRawConfig}from"../context/config-loader.js";import{MODEL_REGISTRY_FILE_NAME,readModelRegistry}from"../api/model-registry-file.js";import{CliErrors}from"../errors.js";import{CLI_BIN_NAME}from"../constant/cli.js";export function resolveApiModelSource(apiDir,appCode,selectedAppName){const absDir=path.resolve(process.cwd(),apiDir);const defaultPath=path.resolve(absDir,"api.ts");const registryPath=path.resolve(absDir,MODEL_REGISTRY_FILE_NAME);const registry=readModelRegistry(registryPath);if(registry){const matches=appCode?Object.entries(registry.profiles).filter(([,profile])=>profile.appCode===appCode):[];if(selectedAppName){if(registry.profiles[selectedAppName]){return{filePath:registryPath,profileName:selectedAppName}}if(matches.length>0){throw CliErrors.validation(`Model profile "${selectedAppName}" is missing from ${MODEL_REGISTRY_FILE_NAME}.`,`Run \`${CLI_BIN_NAME} api pull --app ${selectedAppName}\` first.`)}
|
|
2
|
+
}else{if(matches.length===1){return{filePath:registryPath,profileName:matches[0][0]}}if(matches.length>1){throw new Error(`AppCode "${appCode}" belongs to multiple model profiles: ${matches.map(([name])=>name).join(", ")}. `+"Select the target explicitly with --app <profile>.")}if(registry.profiles[registry.defaultProfile]&&!appCode){return{filePath:registryPath,profileName:registry.defaultProfile}}}}if(!appCode&&!selectedAppName)return{filePath:defaultPath};const config=readRawConfig();const apps=config.apps&&typeof config.apps==="object"?config.apps:{};const matchedEntry=selectedAppName&&apps[selectedAppName]?[selectedAppName,apps[selectedAppName]]:Object.entries(apps).find(([,profile])=>profile?.appcode===appCode);if(!matchedEntry)return{filePath:defaultPath};const[appName,profile]=matchedEntry;const defaultApp=typeof config.defaultApp==="string"?config.defaultApp:undefined;if(profile?.apiDir)return{filePath:defaultPath};if(defaultApp&&appName!==defaultApp){
|
|
3
|
+
const namedPath=path.resolve(absDir,`${appName}-api.ts`);if(existsSync(namedPath))return{filePath:namedPath}}return{filePath:defaultPath}}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{getIsSessionValid}from"../auth/is-session-valid.js";import{authServer}from"../auth/auth-server.js";import{CLI_BIN_NAME}from"../constant/cli.js";import{CliErrors}from"../errors.js";import{confirm}from"@inquirer/prompts";import ora from"ora";export async function runAuthServer(options){const isValid=await getIsSessionValid();if(isValid){console.log("√ Valid session detected, no login required.");return}if(options?.nonInteractive&&!options.autoYes){throw CliErrors.validation("Browser login cannot run in non-interactive mode.",`Run \`${CLI_BIN_NAME} auth login --yes\` and open the printed URL in your browser.`)}const shouldLogin=options?.autoYes?true:await confirm({message:"No valid session. Login now?",default:true});if(!shouldLogin)return;if(options?.nonInteractive){console.log("Starting browser login. Share the printed URL with the user.");const success=await authServer({silent:false,openBrowser:false});if(success){console.log("* Login successful!")}else{
|
|
2
|
+
console.log("! Login failed.")}return}const spinner=ora("Logging in... Please complete login in your browser.").start();const success=await authServer({silent:true,openBrowser:true});spinner.stop();if(success){console.log("* Login successful!")}else{console.log("! Login failed.")}}
|
package/lib/auth/auth-server.js
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{writeFileSync}from"node:fs";import http from"node:http";import https from"node:https";import{getUserDomain}from"../constant/domain.js";import{getOfficialRoutingCdn,getOfficialRoutingProfile}from"../constant/routing-profile.js";import{getProjectDomainRoutingManifest}from"../config/project-domain-routing.js";import{exec}from"node:child_process";import{getIsSessionValid}from"../auth/is-session-valid.js";import{cookieFile}from"../auth/constant.js";import{buildLoginSuccessHtml}from"../auth/login-success-html.js";export const AUTH_LOGIN_TIMEOUT_MS=10*60*1e3;export function resolveAuthCallbackRouting(region){if(!region)return getProjectDomainRoutingManifest().local;const profile=getOfficialRoutingProfile(region);const cdn=getOfficialRoutingCdn(region);return{origin:profile.local.origin,certificateUrl:`${cdn.lovrabet}/cert/lovrabet-dev.json`}}function withPort(origin,port){const url=new URL(origin);url.port=String(port);return url.origin}export async function authServer(params){
|
|
2
|
+
const silent=params?.silent||false;const openBrowser=params?.openBrowser??true;const timeoutMs=params?.timeoutMs??AUTH_LOGIN_TIMEOUT_MS;if(await getIsSessionValid()){return true}const callbackRouting=resolveAuthCallbackRouting();const ssl=callbackRouting.certificateUrl?await(await fetch(callbackRouting.certificateUrl)).json():undefined;return new Promise(async(resolve,reject)=>{let port=0;let settled=false;let timeout;const handleRequest=async(req,res)=>{const userDomain=getUserDomain();const cookie=req.headers.cookie||"";const session=await fetch(`${userDomain}/api/auth/get-session`,{headers:{cookie:cookie}}).then(r=>r.json());const isSuccess=session&&session.session&&session.user;if(isSuccess){writeFileSync(cookieFile,cookie,"utf-8");const html=buildLoginSuccessHtml();res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"});res.end(html);finish(true)}else{const redirect=encodeURIComponent(withPort(callbackRouting.origin,port));res.writeHead(302,{
|
|
3
|
+
location:`${userDomain}/sign-in?redirect=${redirect}`});res.end();return}};const server=ssl?https.createServer(ssl,handleRequest):http.createServer(handleRequest);function finish(success){if(settled)return;settled=true;if(timeout){clearTimeout(timeout)}server.close();resolve(success)}server.listen(0,"127.0.0.1",()=>{const addr=server.address();port=typeof addr==="object"&&addr?addr.port:Number(addr);const loginUrl=withPort(callbackRouting.origin,port);timeout=setTimeout(()=>{if(!silent){console.log("! Login URL expired after 10 minutes. Run the login command again to get a new URL.")}finish(false)},timeoutMs);if(!silent){console.log("🔐 Starting login service...");console.log("📍 Login URL:",loginUrl);if(openBrowser){console.log("🌐 Attempting to open browser automatically...");console.log("");console.log("💡 If the browser does not open automatically, copy the login URL above into your browser.")}else{
|
|
4
|
+
console.log("💡 Open the login URL above in your browser to complete authorization.")}console.log("")}if(!openBrowser){return}openInBrowser(loginUrl).then(success=>{if(!silent){if(success){console.log("✅ Browser opened. Please complete login in the browser.")}else{console.log("⚠️ Failed to open browser automatically");console.log("🔗 Please copy the login URL into your browser:",loginUrl)}console.log("")}}).catch(()=>{if(!silent){console.log("⚠️ Failed to open browser automatically");console.log("🔗 Please copy the login URL into your browser:",loginUrl);console.log("")}})});server.on("error",e=>{if(settled)return;settled=true;if(timeout){clearTimeout(timeout)}if(!silent){console.error("Auth server error:",e)}server.close();reject(e)})})}function openInBrowser(url){return new Promise(resolve=>{const platform=process.platform;let cmd;if(platform==="win32"){cmd=`cmd /c start "" "${url}"`}else if(platform==="darwin"){cmd=`open "${url}"`}else{cmd=`xdg-open "${url}"`}exec(cmd,err=>{
|
|
5
|
+
if(err){resolve(false)}else{resolve(true)}})})}if(import.meta.main){const isAuth=await authServer();console.log("isAuth",isAuth)}
|
package/lib/auth/constant.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";export const configDir=join(homedir(),".lovrabet");export const cookieFile=join(configDir,"cookie");mkdirSync(configDir,{recursive:true});
|
package/lib/auth/get-cookie.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync}from"node:fs";import{cookieFile}from"../auth/constant.js";export function getCookie(){try{return readFileSync(cookieFile,"utf-8")}catch{}return""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{getUserDomain}from"../constant/domain.js";import{cookieFile}from"../auth/constant.js";export async function getSessionUserInfo(cookie){try{if(cookie===undefined){if(!existsSync(cookieFile))return null;cookie=readFileSync(cookieFile,"utf-8")}if(!cookie)return null;const res=await fetch(`${getUserDomain()}/api/auth/get-session`,{headers:{cookie:cookie}});if(!res.ok){return null}const body=await res.json();if(!body.session||!body.user){return null}return body}catch{return null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{getUserDomain}from"../constant/domain.js";import{cookieFile}from"../auth/constant.js";export async function getIsSessionValid(){try{if(!existsSync(cookieFile)){return false}const cookie=readFileSync(cookieFile,"utf-8");const session=await fetch(`${getUserDomain()}/api/auth/get-session`,{headers:{cookie:cookie}}).then(r=>r.json());return session&&session.session&&session.user}catch{}return false}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
function
|
|
1
|
+
export function buildLoginSuccessHtml(){const manualClose="Unable to close automatically. Please close this tab or window manually."
|
|
2
|
+
;return`<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>Login successful · Rabetbase CLI</title>\n <style>\n :root {\n --bg0: #0f1419;\n --bg1: #1a2332;\n --card: #ffffff;\n --text: #1c2128;\n --muted: #5c6570;\n --accent: #2563eb;\n --accent-soft: #eff6ff;\n --success: #059669;\n --radius: 16px;\n --shadow: 0 25px 50px -12px rgba(15, 20, 25, 0.35);\n }\n * { box-sizing: border-box; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,\n "Helvetica Neue", Arial, "Noto Sans", "PingFang SC", "Microsoft YaHei", sans-serif;\n background: linear-gradient(160deg, var(--bg0) 0%, var(--bg1) 45%, #243047 100%);\n color: var(--text);\n }\n .card {\n width: 100%;\n max-width: 420px;\n background: var(--card);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n padding: 40px 36px 32px;\n text-align: center;\n }\n .icon {\n width: 64px;\n height: 64px;\n margin: 0 auto 20px;\n border-radius: 50%;\n background: var(--accent-soft);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .icon svg { width: 36px; height: 36px; }\n h1 {\n margin: 0 0 12px;\n font-size: 1.375rem;\n font-weight: 600;\n letter-spacing: -0.02em;\n }\n p.lead {\n margin: 0 0 8px;\n font-size: 0.9375rem;\n color: var(--muted);\n line-height: 1.55;\n }\n .countdown {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-top: 16px;\n padding: 8px 14px;\n font-size: 0.875rem;\n font-variant-numeric: tabular-nums;\n color: var(--accent);\n background: var(--accent-soft);\n border-radius: 999px;\n font-weight: 500;\n }\n #manualMsg {\n display: none;\n margin-top: 20px;\n font-size: 0.8125rem;\n color: #b91c1c;\n line-height: 1.45;\n }\n .cli-hint {\n margin-top: 28px;\n padding-top: 24px;\n border-top: 1px solid #e8ecf0;\n font-size: 0.75rem;\n color: #8b949e;\n }\n </style>\n</head>\n<body>\n <div class="card" role="status" aria-live="polite">\n <div class="icon" aria-hidden="true">\n <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="12" cy="12" r="10" stroke="#059669" stroke-width="2" fill="none"/>\n <path d="M8 12.5l2.5 2.5L16 9" stroke="#059669" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <h1>Login successful</h1>\n <p class="lead">You can return to the terminal to continue. This window will try to close automatically.</p>\n <div class="countdown">\n Closing in <span id="t">5</span>s\n </div>\n <div id="manualMsg">${manualClose}</div>\n <p class="cli-hint">Rabetbase CLI · session saved locally</p>\n </div>\n <script>\n (function(){\n var t = 5;\n var el = document.getElementById('t');\n var manual = document.getElementById('manualMsg');\n var id = setInterval(function(){\n t--;\n if (t <= 0) {\n clearInterval(id);\n el.textContent = '0';\n try { window.close(); } catch(e) {}\n setTimeout(function(){\n if (!window.closed) {\n manual.style.display = 'block';\n }\n }, 300);\n } else {\n el.textContent = String(t);\n }\n }, 1000);\n })();\n <\/script>\n</body>\n</html>`
|
|
3
|
+
}
|
package/lib/auth/logout.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{unlinkSync,existsSync}from"node:fs";import{cookieFile}from"../auth/constant.js";export function logout(){if(existsSync(cookieFile)){unlinkSync(cookieFile);console.log("✓ Logged out")}else{console.log("! Not logged in")}}
|
package/lib/cli-flags.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export const dynamicCliFlags={enableBffSave:{type:"boolean"}};
|
package/lib/cli.js
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
import meow from"meow";import{showHelp}from"./help.js";import{CliError,CliErrors}from"./errors.js";import{isKnownService,getServiceEntry,findDefinition,resolveRemovedCommand}from"./commands/registry.js";import{runCommand,createPipelineEnv}from"./framework/runner.js";import{formatCliError}from"./framework/output.js";import{resolveErrorOutputFormat,usesStructuredErrorOutput}from"./framework/error-output.js";import{generateCommandHelp,generateServiceHelp,generateFullHelp}from"./framework/help.js";import{CLI_BIN_NAME,buildMeowFlags}from"./constant/cli.js";import{VERSION,GIT_COMMIT,BUILD_TIME}from"./generated/build-info.js";import{reportCliHelpTrace}from"./telemetry/cli-help-trace.js";import{reportCommandTrace}from"./telemetry/cli-command-trace.js";import{registerOtelShutdownOnExit,exitWithOtelShutdown}from"./telemetry/register-otel-exit-shutdown.js";import{printIssueReportNudgeForError}from"./commands/issue/nudge.js";import{assertSupportedCommandFlags}from"./framework/supported-flags.js"
|
|
3
|
+
;let dynamicCliFlags=null;try{dynamicCliFlags=(await(import("./cli-flags.js"))).dynamicCliFlags}catch{}const helpText=generateFullHelp();const cliVersion=GIT_COMMIT!=="unknown"?`${VERSION} (${GIT_COMMIT}, ${BUILD_TIME.slice(0,10)})`:VERSION;const cli=meow(helpText,{importMeta:import.meta,version:cliVersion,flags:{...buildMeowFlags(),...dynamicCliFlags||{}}});registerOtelShutdownOnExit();await run().catch(handleErrorAsync);async function run(){let service=cli.input[0];let command=cli.input[1];const flags=cli.flags;if(!service){await reportCliHelpTrace("global");showHelp();return}const removedCommand=resolveRemovedCommand(service,command);if(removedCommand){await handleErrorAsync(CliErrors.validation(removedCommand.message,removedCommand.hint))}if(!isKnownService(service)){await reportCliHelpTrace("unknown_service",{service:service});showHelp();return}const entry=getServiceEntry(service);if(!command){if(flags.help){printServiceHelp(service);return}if(entry.defaultCommand){
|
|
4
|
+
command=entry.defaultCommand}else if(entry.wildcardDef){const{buildConfigFromFlags:buildConfigFromFlags,initGlobalEnvironment:initGlobalEnvironment}=await(import("./context.js"));const cliConfig=buildConfigFromFlags(flags);await initGlobalEnvironment(cliConfig);await dispatchDeclarative(entry.wildcardDef,service,"",[],flags,cliConfig);return}else{printServiceHelp(service);return}}{let def=findDefinition(service,command);let pipelineArgs=cli.input.slice(2);if(!def){if(entry.wildcardDef){if(flags.help){console.log(generateCommandHelp(entry.wildcardDef));return}def=entry.wildcardDef;pipelineArgs=[command,...cli.input.slice(2)]}else{printServiceHelp(service);await handleErrorAsync(CliErrors.unknownCommand(`${service} ${command}`));return}}assertSupportedCommandFlags(def,flags);if(flags.help){console.log(generateCommandHelp(def));return}
|
|
5
|
+
const{buildConfigFromFlags:buildConfigFromFlags,initGlobalEnvironment:initGlobalEnvironment,isRoutingRecoveryService:isRoutingRecoveryService}=await(import("./context.js"));const cliConfig=buildConfigFromFlags(flags);if(!isRoutingRecoveryService(service)){await initGlobalEnvironment(cliConfig)}await dispatchDeclarative(def,service,command,pipelineArgs,flags,cliConfig)}}async function dispatchDeclarative(def,service,command,pipelineArgs,flags,cliConfig){const startTime=Date.now();let cmdErr;try{await runCommand(def,createPipelineEnv(cliConfig,flags,pipelineArgs))}catch(err){cmdErr=err}await reportCommandTrace({service:service,command:command,flags:flags,durationMs:Date.now()-startTime,error:cmdErr});if(cmdErr){await handleErrorAsync(cmdErr,{service:service,command:command,def:def,flags:flags,defaultFormat:cliConfig.format})}}function printServiceHelp(service){console.log(generateServiceHelp(service))}async function handleErrorAsync(err,currentCommand){
|
|
6
|
+
if(err instanceof Error&&err.name==="ExitPromptError"){process.stderr.write("\nCancelled.\n");return await exitWithOtelShutdown(0)}if(err instanceof CliError){if(err.code==="cancelled"){process.stderr.write(`\n${err.message}\n`);return await exitWithOtelShutdown(0)}let structured=false;if(currentCommand&&usesStructuredErrorOutput(currentCommand.def)){structured=formatCliError(err,{command:`${CLI_BIN_NAME} ${currentCommand.def.service} ${currentCommand.def.command}`,risk:currentCommand.def.risk,format:resolveErrorOutputFormat(currentCommand),jqFilter:typeof currentCommand.flags?.jq==="string"?currentCommand.flags.jq:undefined})}if(!structured){console.error(`Error: ${err.message}`);if(err.hint)console.error(`Hint: ${err.hint}`);if(currentCommand)printIssueReportNudgeForError(err,currentCommand)}return await exitWithOtelShutdown(err.exitCode)}console.error("Unexpected error:",err);if(currentCommand)printIssueReportNudgeForError(err,currentCommand);return await exitWithOtelShutdown(1)}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import ora from"ora";import{fetchModelList}from"../../core/api-client.js";import{generateDatasetDocs}from"../../api/api-doc.js";import{CliErrors}from"../../errors.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{writeCliSideChannelLine}from"../../utils/write-cli-side-channel.js";export const apiGenerate={service:"api",command:"generate",description:"Generate markdown documentation for all datasets",risk:"read",requiresAppCode:true,hasFormat:false,flags:[{...APPCODE_FLAG_OPTIONAL,hidden:true},{name:"output",type:"string",description:"Output directory (default: ./docs)"},{name:"datasetcode",type:"string",description:"Filter: comma-separated dataset codes to generate docs for"},{name:"params",type:"string",description:"Extra params passed to the doc generator (JSON object)"}],async execute(ctx){const outputDir=ctx.str("output")||"./docs";const datasetcodeStr=ctx.str("datasetcode");const paramsStr=ctx.str("params");let extraParams;if(paramsStr){try{
|
|
2
|
+
extraParams=JSON.parse(paramsStr);if(typeof extraParams!=="object"||extraParams===null||Array.isArray(extraParams)){throw new Error("must be a JSON object")}}catch(err){throw CliErrors.validation(`Invalid --params: ${err instanceof Error?err.message:String(err)}`,`Provide a valid JSON object, e.g. --params '{"key":"value"}'`)}}let filterCodes;if(datasetcodeStr){const codes=datasetcodeStr.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(codes.length===0){throw CliErrors.validation("--datasetcode cannot be empty.")}filterCodes=new Set(codes);writeCliSideChannelLine(`[90m* Generating docs for: ${codes.join(", ")}[0m`)}const spinner=ora(`Fetching dataset list for ${ctx.appCode}...`).start();let configArray;try{({configArray:configArray}=await fetchModelList(ctx.appCode,ctx.cookie));spinner.succeed(`Fetched ${configArray.length} dataset(s)`)}catch(err){spinner.fail("Failed to fetch datasets");throw err}if(configArray.length===0){writeCliSideChannelLine("! No datasets found.");return{
|
|
3
|
+
ok:true}}let datasetsToGenerate=configArray;if(filterCodes){datasetsToGenerate=configArray.filter(d=>filterCodes.has(d.datasetCode));const notFound=[...filterCodes].filter(c=>!configArray.some(d=>d.datasetCode===c));if(notFound.length>0){writeCliSideChannelLine(`[33m! The following dataset codes do not exist: ${notFound.join(", ")}[0m`)}if(datasetsToGenerate.length===0){throw CliErrors.validation(`None of the specified dataset codes exist: ${[...filterCodes].join(", ")}`)}writeCliSideChannelLine(`[90m* Filtered ${datasetsToGenerate.length} of ${configArray.length} dataset(s)[0m`)}let current=0;const results=await generateDatasetDocs(datasetsToGenerate,ctx.appCode,ctx.cookie,outputDir,(idx,total,fileName)=>{current=idx;process.stdout.write(`\r [${String(idx).padStart(String(total).length)}/${total}] ${fileName}.md`)},extraParams);if(current>0)process.stdout.write("\n");const succeeded=results.filter(r=>r.success).length;const failed=results.filter(r=>!r.success).length
|
|
4
|
+
;writeCliSideChannelLine("");writeCliSideChannelLine(`✓ Generated ${succeeded} doc(s) in ${outputDir}`);if(failed>0){writeCliSideChannelLine(`! ${failed} doc(s) failed`);for(const r of results.filter(r=>!r.success)){writeCliSideChannelLine(` • ${r.datasetName} (${r.datasetCode}): ${r.error}`)}}return{ok:failed===0,message:failed>0?`Doc generation: ${succeeded} succeeded, ${failed} failed`:`Doc generation complete: ${succeeded} file(s)`}}};
|