bpmax-cli 0.1.44-beta.8 → 0.1.44
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 +5 -3
- package/dist/bin.js +466 -4578
- package/dist/bin.js.map +1 -1
- package/package.json +1 -1
- package/scripts/install-skills.mjs +0 -98
- package/skills/bpmax-auth/SKILL.md +17 -6
- package/skills/bpmax-cli/SKILL.md +0 -2
- package/skills/bpmax-project/SKILL.md +2 -1
- package/skills/bpmax-shared/SKILL.md +1 -1
- package/skills/bpmax-api-platform-editor/SKILL.md +0 -321
- package/skills/bpmax-api-platform-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-api-platform-editor/references/api-doc-debug-workflow.md +0 -34
- package/skills/bpmax-api-platform-editor/references/api-proxy-shape.md +0 -41
- package/skills/bpmax-api-platform-editor/references/instance-config-shape.md +0 -41
- package/skills/bpmax-api-platform-editor/references/platform-api-map.md +0 -52
- package/skills/bpmax-api-platform-editor/references/runtime-workflow.md +0 -32
- package/skills/bpmax-api-platform-editor/scripts/api_platform_editor_common.py +0 -1276
- package/skills/bpmax-api-platform-editor/scripts/build_submit_payload.py +0 -64
- package/skills/bpmax-api-platform-editor/scripts/capture_write_contract.py +0 -40
- package/skills/bpmax-api-platform-editor/scripts/export_layer_bundle.py +0 -212
- package/skills/bpmax-api-platform-editor/scripts/record_doc_debug_acceptance.py +0 -62
- package/skills/bpmax-api-platform-editor/scripts/submit_and_verify_layer.py +0 -75
- package/skills/bpmax-api-platform-editor/tests/test_api_platform_editor.py +0 -287
- package/skills/bpmax-builder-shared/SKILL.md +0 -44
- package/skills/bpmax-builder-shared/base_url.py +0 -81
- package/skills/bpmax-builder-shared/runtime-script-site-matrix.json +0 -71
- package/skills/bpmax-builder-shared/runtime-script-site-matrix.md +0 -34
- package/skills/bpmax-builder-shared/runtime-script-template-catalog.md +0 -123
- package/skills/bpmax-builder-shared/runtime_script_rules.py +0 -272
- package/skills/bpmax-builder-shared/skill_audit.py +0 -374
- package/skills/bpmax-builder-shared/template_script_hard_rules.py +0 -280
- package/skills/bpmax-builder-shared/tests/test_base_url.py +0 -80
- package/skills/bpmax-builder-shared/tests/test_runtime_script_rules.py +0 -115
- package/skills/bpmax-builder-shared/tests/test_skill_audit.py +0 -231
- package/skills/bpmax-builder-shared/tests/test_template_script_hard_rules.py +0 -281
- package/skills/bpmax-config-latest/SKILL.md +0 -71
- package/skills/bpmax-console-template-editor/SKILL.md +0 -536
- package/skills/bpmax-console-template-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-console-template-editor/references/filter-integration.md +0 -60
- package/skills/bpmax-console-template-editor/references/lessons-from-resume-dashboard.md +0 -114
- package/skills/bpmax-console-template-editor/references/local-temp-workflow.md +0 -69
- package/skills/bpmax-console-template-editor/references/module-catalog.md +0 -100
- package/skills/bpmax-console-template-editor/references/runtime-page-shape.md +0 -91
- package/skills/bpmax-console-template-editor/references/template-shape.md +0 -149
- package/skills/bpmax-console-template-editor/scripts/build_submit_payload.py +0 -38
- package/skills/bpmax-console-template-editor/scripts/confirm_console_template.py +0 -33
- package/skills/bpmax-console-template-editor/scripts/console_template_editor_common.py +0 -964
- package/skills/bpmax-console-template-editor/scripts/export_console_template.py +0 -99
- package/skills/bpmax-console-template-editor/scripts/lint_console_template.py +0 -46
- package/skills/bpmax-console-template-editor/scripts/submit_console_template.py +0 -99
- package/skills/bpmax-console-template-editor/tests/test_console_template_editor.py +0 -383
- package/skills/bpmax-dataset-field-template-editor/SKILL.md +0 -600
- package/skills/bpmax-dataset-field-template-editor/references/create-request-gotchas.md +0 -25
- package/skills/bpmax-dataset-field-template-editor/references/field-classify-mapping.md +0 -35
- package/skills/bpmax-dataset-field-template-editor/references/nested-field-patterns.md +0 -24
- package/skills/bpmax-dataset-field-template-editor/references/runtime-verified-field-page-shape.md +0 -61
- package/skills/bpmax-dataset-field-template-editor/references/virtual-field-patterns.md +0 -27
- package/skills/bpmax-dataset-field-template-editor/references/work-file-to-submit-mapping.md +0 -127
- package/skills/bpmax-dataset-field-template-editor/scripts/build_submit_payload.py +0 -67
- package/skills/bpmax-dataset-field-template-editor/scripts/confirm_dataset_field.py +0 -37
- package/skills/bpmax-dataset-field-template-editor/scripts/dataset_field_editor_common.py +0 -784
- package/skills/bpmax-dataset-field-template-editor/scripts/export_dataset_field.py +0 -62
- package/skills/bpmax-dataset-field-template-editor/scripts/init_create_dataset_field.py +0 -104
- package/skills/bpmax-dataset-field-template-editor/scripts/inspect_dataset_field_runtime.py +0 -83
- package/skills/bpmax-dataset-field-template-editor/scripts/lint_dataset_field_semantics.py +0 -35
- package/skills/bpmax-dataset-field-template-editor/scripts/submit_dataset_field.py +0 -95
- package/skills/bpmax-dataset-field-template-editor/tests/test_dataset_field_editor.py +0 -709
- package/skills/bpmax-dataset-field-template-editor/tests/test_init_create_dataset_field.py +0 -59
- package/skills/bpmax-dataset-template-editor/SKILL.md +0 -779
- package/skills/bpmax-dataset-template-editor/references/custom-key-usage-patterns.md +0 -18
- package/skills/bpmax-dataset-template-editor/references/dataset-script-runtime-matrix.md +0 -73
- package/skills/bpmax-dataset-template-editor/references/pre-process-script-authoring-guide.md +0 -186
- package/skills/bpmax-dataset-template-editor/references/pre-process-script-example-catalog.md +0 -106
- package/skills/bpmax-dataset-template-editor/references/runtime-gotchas.md +0 -28
- package/skills/bpmax-dataset-template-editor/references/runtime-verified-dataset-page-shape.md +0 -47
- package/skills/bpmax-dataset-template-editor/references/ui-to-backend-field-map.md +0 -23
- package/skills/bpmax-dataset-template-editor/references/work-file-to-submit-mapping.md +0 -97
- package/skills/bpmax-dataset-template-editor/scripts/basic_table_audit.py +0 -65
- package/skills/bpmax-dataset-template-editor/scripts/build_submit_payload.py +0 -38
- package/skills/bpmax-dataset-template-editor/scripts/dataset_editor_common.py +0 -650
- package/skills/bpmax-dataset-template-editor/scripts/export_dataset.py +0 -155
- package/skills/bpmax-dataset-template-editor/scripts/lint_dataset_template.py +0 -42
- package/skills/bpmax-dataset-template-editor/scripts/resolve_dataset.py +0 -43
- package/skills/bpmax-dataset-template-editor/scripts/scan_custom_key_references.py +0 -27
- package/skills/bpmax-dataset-template-editor/scripts/submit_dataset.py +0 -115
- package/skills/bpmax-dataset-template-editor/scripts/verify_dataset_list.py +0 -52
- package/skills/bpmax-dataset-template-editor/scripts/verify_publish_health.py +0 -39
- package/skills/bpmax-dataset-template-editor/tests/test_dataset_editor.py +0 -373
- package/skills/bpmax-e2e-flow-config-orchestrator/SKILL.md +0 -177
- package/skills/bpmax-e2e-flow-config-orchestrator/agents/openai.yaml +0 -4
- package/skills/bpmax-e2e-flow-config-orchestrator/references/orchestration-matrix.md +0 -60
- package/skills/bpmax-e2e-flow-test-operator/SKILL.md +0 -394
- package/skills/bpmax-e2e-flow-test-operator/agents/openai.yaml +0 -5
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale.json +0 -97
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_final_v2.json +0 -105
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_main.json +0 -36
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_region.json +0 -40
- package/skills/bpmax-e2e-flow-test-operator/references/browser-only-checkpoints.md +0 -41
- package/skills/bpmax-e2e-flow-test-operator/references/failure-update-loop.md +0 -17
- package/skills/bpmax-e2e-flow-test-operator/references/filter-field-discovery.md +0 -40
- package/skills/bpmax-e2e-flow-test-operator/references/minimal-test-loop.md +0 -24
- package/skills/bpmax-e2e-flow-test-operator/references/negative-sale-api-matrix.md +0 -75
- package/skills/bpmax-e2e-flow-test-operator/references/profile-schema.md +0 -107
- package/skills/bpmax-e2e-flow-test-operator/references/skill-experience-coverage-matrix.md +0 -29
- package/skills/bpmax-e2e-flow-test-operator/references/stale-runtime-and-clean-sample-rules.md +0 -54
- package/skills/bpmax-e2e-flow-test-operator/references/state-schema.md +0 -83
- package/skills/bpmax-e2e-flow-test-operator/scripts/bpmax_session.py +0 -287
- package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_plan.json +0 -59
- package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_runner.py +0 -687
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_doc.py +0 -121
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_state.py +0 -288
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_api_matrix.py +0 -161
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_filter_fields.py +0 -138
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_form_runtime.py +0 -396
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_runner.py +0 -341
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_test_profile.py +0 -185
- package/skills/bpmax-e2e-flow-test-operator/tests/test_negative_sale_api_tools.py +0 -138
- package/skills/bpmax-feishu-chat-flow-plugin-editor/SKILL.md +0 -69
- package/skills/bpmax-feishu-chat-flow-plugin-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-checklist.md +0 -42
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-recipes.md +0 -38
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-shape.md +0 -86
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/gate-lint.md +0 -68
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/hoocoo-patterns.md +0 -39
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/runtime-behavior.md +0 -41
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/script-authoring.md +0 -110
- package/skills/bpmax-feishu-chat-flow-plugin-editor/scripts/lint_feishu_chat_plugin.py +0 -278
- package/skills/bpmax-feishu-chat-flow-plugin-editor/tests/test_lint_feishu_chat_plugin.py +0 -203
- package/skills/bpmax-filter-template-editor/SKILL.md +0 -564
- package/skills/bpmax-filter-template-editor/references/experience-coverage-matrix.md +0 -38
- package/skills/bpmax-filter-template-editor/references/filter-and-flow-binding.md +0 -57
- package/skills/bpmax-filter-template-editor/references/filter-content-schema.md +0 -141
- package/skills/bpmax-filter-template-editor/references/filter-request-shape.md +0 -287
- package/skills/bpmax-filter-template-editor/references/filter-runtime-patterns.md +0 -115
- package/skills/bpmax-filter-template-editor/references/runtime-verified-filter-page-shape.md +0 -94
- package/skills/bpmax-filter-template-editor/scripts/build_submit_payload.py +0 -25
- package/skills/bpmax-filter-template-editor/scripts/confirm_filter_template.py +0 -22
- package/skills/bpmax-filter-template-editor/scripts/export_filter_template.py +0 -57
- package/skills/bpmax-filter-template-editor/scripts/filter_template_editor_common.py +0 -348
- package/skills/bpmax-filter-template-editor/scripts/init_create_filter_template.py +0 -8
- package/skills/bpmax-filter-template-editor/scripts/lint_filter_template_semantics.py +0 -26
- package/skills/bpmax-filter-template-editor/scripts/submit_filter_template.py +0 -62
- package/skills/bpmax-filter-template-editor/tests/test_filter_template_editor.py +0 -231
- package/skills/bpmax-flow-template-editor/SKILL.md +0 -1058
- package/skills/bpmax-flow-template-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-flow-template-editor/references/before-next-step-script-runtime-gotchas.md +0 -62
- package/skills/bpmax-flow-template-editor/references/config-surfaces-and-placeholders.md +0 -270
- package/skills/bpmax-flow-template-editor/references/diff-strategy.md +0 -67
- package/skills/bpmax-flow-template-editor/references/editor-runtime-vs-draft.md +0 -25
- package/skills/bpmax-flow-template-editor/references/flow-template-api-workflow.md +0 -174
- package/skills/bpmax-flow-template-editor/references/intent-model.md +0 -117
- package/skills/bpmax-flow-template-editor/references/lessons-from-price-plan-flow.md +0 -147
- package/skills/bpmax-flow-template-editor/references/local-temp-workflow.md +0 -97
- package/skills/bpmax-flow-template-editor/references/matrix-flow-form-nav-collaboration.md +0 -165
- package/skills/bpmax-flow-template-editor/references/payload-checklist.md +0 -133
- package/skills/bpmax-flow-template-editor/references/project-create-runtime-gotchas.md +0 -54
- package/skills/bpmax-flow-template-editor/references/requirement-to-node-mapping.md +0 -149
- package/skills/bpmax-flow-template-editor/references/runtime-verified-flow-detail-shape.md +0 -41
- package/skills/bpmax-flow-template-editor/references/runtime-verified-meta-fields.md +0 -155
- package/skills/bpmax-flow-template-editor/references/runtime-verified-node-fields.md +0 -179
- package/skills/bpmax-flow-template-editor/references/save-draft-request-shape.md +0 -91
- package/skills/bpmax-flow-template-editor/references/script-review-hard-rules.md +0 -93
- package/skills/bpmax-flow-template-editor/references/work-file-to-submit-mapping.md +0 -57
- package/skills/bpmax-flow-template-editor/scripts/build_submit_payload.py +0 -69
- package/skills/bpmax-flow-template-editor/scripts/confirm_flow_template.py +0 -52
- package/skills/bpmax-flow-template-editor/scripts/export_flow_template.py +0 -114
- package/skills/bpmax-flow-template-editor/scripts/flow_template_editor_common.py +0 -1084
- package/skills/bpmax-flow-template-editor/scripts/submit_flow_template.py +0 -159
- package/skills/bpmax-flow-template-editor/tests/test_flow_template_editor.py +0 -636
- package/skills/bpmax-form-template-editor/SKILL.md +0 -1099
- package/skills/bpmax-form-template-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-form-template-editor/references/form-template-api-workflow.md +0 -203
- package/skills/bpmax-form-template-editor/references/local-temp-workflow.md +0 -125
- package/skills/bpmax-form-template-editor/references/payload-checklist.md +0 -77
- package/skills/bpmax-form-template-editor/references/sub-form-patterns.md +0 -49
- package/skills/bpmax-form-template-editor/scripts/build_submit_payload.py +0 -37
- package/skills/bpmax-form-template-editor/scripts/check_form_template_consistency.py +0 -145
- package/skills/bpmax-form-template-editor/scripts/confirm_form_template.py +0 -67
- package/skills/bpmax-form-template-editor/scripts/export_form_template.py +0 -91
- package/skills/bpmax-form-template-editor/scripts/form_template_editor_common.py +0 -1762
- package/skills/bpmax-form-template-editor/scripts/lint_form_template_semantics.py +0 -30
- package/skills/bpmax-form-template-editor/scripts/record_runtime_acceptance.py +0 -67
- package/skills/bpmax-form-template-editor/scripts/submit_form_template.py +0 -163
- package/skills/bpmax-form-template-editor/tests/test_form_template_editor.py +0 -1292
- package/skills/bpmax-list-template-editor/SKILL.md +0 -468
- package/skills/bpmax-list-template-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-list-template-editor/references/browser-page-contract.md +0 -81
- package/skills/bpmax-list-template-editor/references/content-config-shape.md +0 -148
- package/skills/bpmax-list-template-editor/references/dataset-field-mapping.md +0 -60
- package/skills/bpmax-list-template-editor/references/list-template-api-workflow.md +0 -103
- package/skills/bpmax-list-template-editor/references/local-temp-workflow.md +0 -102
- package/skills/bpmax-list-template-editor/references/payload-checklist.md +0 -47
- package/skills/bpmax-list-template-editor/references/runtime-verified-workflow.md +0 -140
- package/skills/bpmax-list-template-editor/references/special-formats.md +0 -394
- package/skills/bpmax-list-template-editor/scripts/build_submit_payload.py +0 -37
- package/skills/bpmax-list-template-editor/scripts/confirm_list_template.py +0 -33
- package/skills/bpmax-list-template-editor/scripts/export_list_template.py +0 -89
- package/skills/bpmax-list-template-editor/scripts/fetch_data_set.py +0 -34
- package/skills/bpmax-list-template-editor/scripts/lint_list_template_semantics.py +0 -54
- package/skills/bpmax-list-template-editor/scripts/list_template_editor_common.py +0 -955
- package/skills/bpmax-list-template-editor/scripts/record_acceptance.py +0 -55
- package/skills/bpmax-list-template-editor/scripts/submit_list_template.py +0 -117
- package/skills/bpmax-list-template-editor/tests/test_list_template_editor_common.py +0 -441
- package/skills/bpmax-memory-protocol/SKILL.md +0 -72
- package/skills/bpmax-nav-config-editor/SKILL.md +0 -347
- package/skills/bpmax-nav-config-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-nav-config-editor/references/api-workflow.md +0 -68
- package/skills/bpmax-nav-config-editor/references/config-shape.md +0 -78
- package/skills/bpmax-nav-config-editor/references/icon-selection.md +0 -83
- package/skills/bpmax-nav-config-editor/references/path-mapping-rules.md +0 -46
- package/skills/bpmax-nav-config-editor/references/payload-checklist.md +0 -41
- package/skills/bpmax-nav-config-editor/references/runtime-probing.md +0 -47
- package/skills/bpmax-nav-config-editor/scripts/build_submit_payload.py +0 -34
- package/skills/bpmax-nav-config-editor/scripts/confirm_nav_config.py +0 -32
- package/skills/bpmax-nav-config-editor/scripts/export_nav_config.py +0 -56
- package/skills/bpmax-nav-config-editor/scripts/lint_nav_config_semantics.py +0 -33
- package/skills/bpmax-nav-config-editor/scripts/nav_config_editor_common.py +0 -812
- package/skills/bpmax-nav-config-editor/scripts/submit_nav_config.py +0 -44
- package/skills/bpmax-nav-config-editor/scripts/verify_nav_config.py +0 -33
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor.py +0 -358
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor_common.py +0 -138
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_lint.py +0 -58
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_submit_verify.py +0 -51
- package/skills/bpmax-project-detail-template-editor/SKILL.md +0 -329
- package/skills/bpmax-project-detail-template-editor/agents/openai.yaml +0 -4
- package/skills/bpmax-project-detail-template-editor/references/local-temp-workflow.md +0 -59
- package/skills/bpmax-project-detail-template-editor/references/module-catalog-and-config-notes.md +0 -47
- package/skills/bpmax-project-detail-template-editor/references/payload-checklist.md +0 -33
- package/skills/bpmax-project-detail-template-editor/references/project-detail-template-api-workflow.md +0 -44
- package/skills/bpmax-project-detail-template-editor/scripts/build_submit_payload.py +0 -30
- package/skills/bpmax-project-detail-template-editor/scripts/confirm_project_detail_template.py +0 -33
- package/skills/bpmax-project-detail-template-editor/scripts/export_project_detail_template.py +0 -87
- package/skills/bpmax-project-detail-template-editor/scripts/lint_project_detail_template_semantics.py +0 -37
- package/skills/bpmax-project-detail-template-editor/scripts/project_detail_template_editor_common.py +0 -507
- package/skills/bpmax-project-detail-template-editor/scripts/submit_project_detail_template.py +0 -120
- package/skills/bpmax-project-detail-template-editor/tests/test_project_detail_template_editor.py +0 -369
- package/skills/bpmax-role-editor/SKILL.md +0 -251
- package/skills/bpmax-role-editor/references/api-workflow.md +0 -30
- package/skills/bpmax-role-editor/references/runtime-page-shape.md +0 -18
- package/skills/bpmax-role-editor/references/work-file-mapping.md +0 -32
- package/skills/bpmax-role-editor/scripts/build_submit_payload.py +0 -38
- package/skills/bpmax-role-editor/scripts/confirm_role.py +0 -33
- package/skills/bpmax-role-editor/scripts/export_role.py +0 -163
- package/skills/bpmax-role-editor/scripts/lint_role_semantics.py +0 -38
- package/skills/bpmax-role-editor/scripts/role_editor_common.py +0 -1231
- package/skills/bpmax-role-editor/scripts/submit_role.py +0 -144
- package/skills/bpmax-role-editor/tests/test_role_editor.py +0 -343
- package/skills/bpmax-user-mock-operator/SKILL.md +0 -106
- package/skills/bpmax-user-mock-operator/agents/openai.yaml +0 -4
- package/skills/bpmax-user-mock-operator/scripts/switch_user_identity.py +0 -37
- package/skills/bpmax-user-mock-operator/scripts/user_mock_operator_common.py +0 -136
- package/skills/bpmax-user-mock-operator/tests/test_user_mock_operator.py +0 -138
- package/skills/form-control-library/SKILL.md +0 -82
- package/skills/form-control-library/agents/openai.yaml +0 -4
- package/skills/form-control-library/references/form-controls.md +0 -199
- package/skills/form-control-library/references/form-template-submit-schema.md +0 -180
- package/skills/form-control-library/references/group-select-runtime.md +0 -191
- package/skills/form-control-library/scripts/rebuild_form_control_library.py +0 -55
|
@@ -1,1276 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import ast
|
|
5
|
-
import copy
|
|
6
|
-
import hashlib
|
|
7
|
-
import json
|
|
8
|
-
import os
|
|
9
|
-
import re
|
|
10
|
-
import shlex
|
|
11
|
-
import ssl
|
|
12
|
-
import sys
|
|
13
|
-
import urllib.error
|
|
14
|
-
import urllib.parse
|
|
15
|
-
import urllib.request
|
|
16
|
-
from dataclasses import dataclass
|
|
17
|
-
from datetime import datetime, timezone
|
|
18
|
-
from difflib import unified_diff
|
|
19
|
-
from pathlib import Path
|
|
20
|
-
from typing import Any, Dict, Iterable, Mapping, Optional, Sequence
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
SHARED_SKILL_ROOT = Path(__file__).resolve().parents[2] / "bpmax-builder-shared"
|
|
24
|
-
if str(SHARED_SKILL_ROOT) not in sys.path:
|
|
25
|
-
sys.path.insert(0, str(SHARED_SKILL_ROOT))
|
|
26
|
-
|
|
27
|
-
from base_url import BASE_URL_ENV_VAR, resolve_base_url
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
DEFAULT_LANGUAGE = "zhCN"
|
|
31
|
-
REPO_ROOT = Path(__file__).resolve().parents[4]
|
|
32
|
-
AGENTS_PATH = REPO_ROOT / "AGENTS.md"
|
|
33
|
-
TMP_ROOT = REPO_ROOT / ".codex" / "tmp" / "api-platform-editor"
|
|
34
|
-
TMP_SUBDIRS = ("raw", "work", "meta", "submit", "diffs", "result", "contracts", "fragments", "context")
|
|
35
|
-
VALID_LAYERS = {"platform", "instance", "api", "doc-debug"}
|
|
36
|
-
VALID_MODES = {"create", "update"}
|
|
37
|
-
SCRIPT_FIELD_NAMES = ("on_setup_script", "on_request_script", "on_response_script", "on_error_script")
|
|
38
|
-
API_SIDECAR_NAMES = (
|
|
39
|
-
"request_schema",
|
|
40
|
-
"response_schema",
|
|
41
|
-
"request_example",
|
|
42
|
-
"response_example",
|
|
43
|
-
"response_binding",
|
|
44
|
-
)
|
|
45
|
-
CONTRACT_HEADER_WHITELIST = {
|
|
46
|
-
"accept",
|
|
47
|
-
"accept-language",
|
|
48
|
-
"content-type",
|
|
49
|
-
"x-requested-with",
|
|
50
|
-
}
|
|
51
|
-
DROP_IDENTITY_KEYS = {
|
|
52
|
-
"id",
|
|
53
|
-
"guid",
|
|
54
|
-
"created_at",
|
|
55
|
-
"create_time",
|
|
56
|
-
"updated_at",
|
|
57
|
-
"update_time",
|
|
58
|
-
"deleted_at",
|
|
59
|
-
"is_del",
|
|
60
|
-
"organization_id",
|
|
61
|
-
"workspace",
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def utc_now_iso() -> str:
|
|
66
|
-
return datetime.now(timezone.utc).isoformat()
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def ensure_tmp_dirs() -> None:
|
|
70
|
-
for part in TMP_SUBDIRS:
|
|
71
|
-
(TMP_ROOT / part).mkdir(parents=True, exist_ok=True)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
def paths_for(stem: str) -> Dict[str, Path]:
|
|
75
|
-
ensure_tmp_dirs()
|
|
76
|
-
return {
|
|
77
|
-
"raw": TMP_ROOT / "raw" / f"{stem}.json",
|
|
78
|
-
"work": TMP_ROOT / "work" / f"{stem}.json",
|
|
79
|
-
"meta": TMP_ROOT / "meta" / f"{stem}.json",
|
|
80
|
-
"submit": TMP_ROOT / "submit" / f"{stem}.json",
|
|
81
|
-
"work_diff": TMP_ROOT / "diffs" / f"{stem}.work.diff.txt",
|
|
82
|
-
"submit_diff": TMP_ROOT / "diffs" / f"{stem}.submit.diff.txt",
|
|
83
|
-
"response": TMP_ROOT / "result" / f"{stem}.response.json",
|
|
84
|
-
"readback": TMP_ROOT / "result" / f"{stem}.readback.json",
|
|
85
|
-
"verify": TMP_ROOT / "result" / f"{stem}.verify.json",
|
|
86
|
-
"drift": TMP_ROOT / "result" / f"{stem}.drift.json",
|
|
87
|
-
"acceptance": TMP_ROOT / "result" / f"{stem}.acceptance.json",
|
|
88
|
-
"fragments": TMP_ROOT / "fragments" / stem,
|
|
89
|
-
"context": TMP_ROOT / "context" / f"{stem}.json",
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def default_contract_path(layer: str, mode: str) -> Path:
|
|
94
|
-
ensure_tmp_dirs()
|
|
95
|
-
return TMP_ROOT / "contracts" / f"{layer}.{mode}.json"
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def dump_json(path: Path, payload: Any) -> None:
|
|
99
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
-
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def load_json(path: Path) -> Any:
|
|
104
|
-
return json.loads(path.read_text(encoding="utf-8"))
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def load_text(path: Path) -> str:
|
|
108
|
-
return path.read_text(encoding="utf-8")
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def file_sha256(path: Path) -> str:
|
|
112
|
-
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def stable_json_lines(payload: Any) -> list[str]:
|
|
116
|
-
return (json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n").splitlines(keepends=True)
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
def write_diff(path: Path, before: Any, after: Any, before_label: str, after_label: str) -> None:
|
|
120
|
-
diff = unified_diff(stable_json_lines(before), stable_json_lines(after), fromfile=before_label, tofile=after_label)
|
|
121
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
-
path.write_text("".join(diff) or "# no diff\n", encoding="utf-8")
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def sanitize_stem_fragment(value: Any) -> str:
|
|
126
|
-
text = str(value or "").strip().lower()
|
|
127
|
-
text = re.sub(r"[^a-z0-9._-]+", "-", text)
|
|
128
|
-
return text.strip("-") or "unknown"
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def make_stem(layer: str, mode: str, *, platform_key: str | None = None, remote_id: Any | None = None) -> str:
|
|
132
|
-
base = sanitize_stem_fragment(layer)
|
|
133
|
-
if layer == "platform":
|
|
134
|
-
suffix = sanitize_stem_fragment(platform_key or remote_id or mode)
|
|
135
|
-
return f"{'create-' if mode == 'create' else ''}{base}-{suffix}"
|
|
136
|
-
if layer == "doc-debug":
|
|
137
|
-
suffix = sanitize_stem_fragment(platform_key or "platform")
|
|
138
|
-
return f"{base}-{suffix}-{sanitize_stem_fragment(remote_id or mode)}"
|
|
139
|
-
suffix = sanitize_stem_fragment(remote_id or platform_key or mode)
|
|
140
|
-
return f"{'create-' if mode == 'create' else ''}{base}-{suffix}"
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
def _trim_trailing_punctuation(value: str) -> str:
|
|
144
|
-
return value.rstrip(").,;]")
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
def _extract_origin_candidate(value: str | None) -> str:
|
|
148
|
-
text = str(value or "").strip()
|
|
149
|
-
if not text:
|
|
150
|
-
return ""
|
|
151
|
-
parsed = urllib.parse.urlparse(text)
|
|
152
|
-
if parsed.scheme in ("http", "https") and parsed.netloc:
|
|
153
|
-
return f"{parsed.scheme}://{parsed.netloc}"
|
|
154
|
-
return text
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
def read_repo_default_origin(*, agents_path: Path = AGENTS_PATH) -> str | None:
|
|
158
|
-
if not agents_path.exists():
|
|
159
|
-
return None
|
|
160
|
-
text = agents_path.read_text(encoding="utf-8")
|
|
161
|
-
patterns = (
|
|
162
|
-
r"(?im)^\s*BPMAX_DEFAULT_ORIGIN\s*[:=]\s*(https?://\S+)",
|
|
163
|
-
r"(?im)^\s*DEFAULT_BPMAX_APP_ORIGIN\s*[:=]\s*(https?://\S+)",
|
|
164
|
-
r"(?im)default\s+bpmax\s+app\s+origin[^:\n=]*[:=]\s*(https?://\S+)",
|
|
165
|
-
r"(?im)仓库默认.*?origin[^:\n=]*[:=]\s*(https?://\S+)",
|
|
166
|
-
)
|
|
167
|
-
for pattern in patterns:
|
|
168
|
-
match = re.search(pattern, text)
|
|
169
|
-
if match:
|
|
170
|
-
return _trim_trailing_punctuation(match.group(1))
|
|
171
|
-
return None
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
def resolve_editor_base_url(
|
|
175
|
-
value: str | None,
|
|
176
|
-
*,
|
|
177
|
-
browser_origin: str | None = None,
|
|
178
|
-
env: Mapping[str, str] | None = None,
|
|
179
|
-
agents_path: Path = AGENTS_PATH,
|
|
180
|
-
) -> str:
|
|
181
|
-
env_map = os.environ if env is None else env
|
|
182
|
-
if value not in (None, ""):
|
|
183
|
-
return resolve_base_url(value, env={})
|
|
184
|
-
env_value = env_map.get(BASE_URL_ENV_VAR, "")
|
|
185
|
-
if env_value:
|
|
186
|
-
return resolve_base_url(None, env=env_map)
|
|
187
|
-
browser_candidate = _extract_origin_candidate(browser_origin)
|
|
188
|
-
if browser_candidate:
|
|
189
|
-
return resolve_base_url(browser_candidate, env={})
|
|
190
|
-
repo_default = read_repo_default_origin(agents_path=agents_path)
|
|
191
|
-
if repo_default:
|
|
192
|
-
return resolve_base_url(repo_default, env={})
|
|
193
|
-
raise SystemExit(
|
|
194
|
-
"missing BPMAX base url: pass --base-url, set BPMAX_BASE_URL, provide the current browser origin, "
|
|
195
|
-
"or add a repo default origin contract in AGENTS.md"
|
|
196
|
-
)
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
def load_meta(path: Path) -> Dict[str, Any]:
|
|
200
|
-
if not path.exists():
|
|
201
|
-
return {}
|
|
202
|
-
payload = load_json(path)
|
|
203
|
-
if not isinstance(payload, dict):
|
|
204
|
-
raise SystemExit(f"invalid meta file, expected object: {path}")
|
|
205
|
-
return payload
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
def save_meta(path: Path, payload: Dict[str, Any]) -> None:
|
|
209
|
-
dump_json(path, payload)
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
def ensure_meta_shape(meta: Dict[str, Any], *, stem: str, layer: str, mode: str) -> Dict[str, Any]:
|
|
213
|
-
payload = dict(meta)
|
|
214
|
-
payload["stem"] = stem
|
|
215
|
-
payload["layer"] = layer
|
|
216
|
-
payload["mode"] = mode
|
|
217
|
-
payload.setdefault("status", "exported")
|
|
218
|
-
payload.setdefault("workSha256", None)
|
|
219
|
-
payload.setdefault("submitSha256", None)
|
|
220
|
-
payload.setdefault("contractSha256", None)
|
|
221
|
-
payload.setdefault("workConfirmedAt", None)
|
|
222
|
-
payload.setdefault("workConfirmedBy", None)
|
|
223
|
-
payload.setdefault("submitBuiltAt", None)
|
|
224
|
-
payload.setdefault("submitConfirmedAt", None)
|
|
225
|
-
payload.setdefault("submitConfirmedBy", None)
|
|
226
|
-
payload.setdefault("submittedAt", None)
|
|
227
|
-
payload.setdefault("verification", {})
|
|
228
|
-
payload.setdefault(
|
|
229
|
-
"runtimeAcceptance",
|
|
230
|
-
{
|
|
231
|
-
"required": layer in {"instance", "api"},
|
|
232
|
-
"recordedAt": None,
|
|
233
|
-
"result": None,
|
|
234
|
-
"docDebugStem": None,
|
|
235
|
-
},
|
|
236
|
-
)
|
|
237
|
-
return payload
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
def write_export_meta(
|
|
241
|
-
meta_path: Path,
|
|
242
|
-
*,
|
|
243
|
-
stem: str,
|
|
244
|
-
layer: str,
|
|
245
|
-
mode: str,
|
|
246
|
-
work_path: Path,
|
|
247
|
-
workspace: str | None,
|
|
248
|
-
platform_key: str | None,
|
|
249
|
-
platform_guid: str | None,
|
|
250
|
-
remote_id: Any | None,
|
|
251
|
-
remote_guid: str | None,
|
|
252
|
-
browser_origin: str | None = None,
|
|
253
|
-
doc_debug_stem: str | None = None,
|
|
254
|
-
) -> Dict[str, Any]:
|
|
255
|
-
payload = ensure_meta_shape(load_meta(meta_path), stem=stem, layer=layer, mode=mode)
|
|
256
|
-
payload["workspace"] = workspace
|
|
257
|
-
payload["platformKey"] = platform_key
|
|
258
|
-
payload["platformGuid"] = platform_guid
|
|
259
|
-
payload["remoteId"] = remote_id
|
|
260
|
-
payload["remoteGuid"] = remote_guid
|
|
261
|
-
payload["browserOrigin"] = _extract_origin_candidate(browser_origin) or None
|
|
262
|
-
payload["repoDefaultOrigin"] = read_repo_default_origin()
|
|
263
|
-
payload["workSha256"] = file_sha256(work_path) if work_path.exists() else None
|
|
264
|
-
payload["submitSha256"] = None
|
|
265
|
-
payload["contractSha256"] = None
|
|
266
|
-
payload["submitBuiltAt"] = None
|
|
267
|
-
payload["submitConfirmedAt"] = None
|
|
268
|
-
payload["submitConfirmedBy"] = None
|
|
269
|
-
payload["submittedAt"] = None
|
|
270
|
-
payload["verification"] = {}
|
|
271
|
-
payload["runtimeAcceptance"]["required"] = layer in {"instance", "api"}
|
|
272
|
-
payload["runtimeAcceptance"]["docDebugStem"] = doc_debug_stem
|
|
273
|
-
payload["status"] = "exported"
|
|
274
|
-
save_meta(meta_path, payload)
|
|
275
|
-
return payload
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
def record_work_confirmation(meta_path: Path, *, actor: str, work_path: Path) -> Dict[str, Any]:
|
|
279
|
-
raw = load_meta(meta_path)
|
|
280
|
-
if not raw:
|
|
281
|
-
raise SystemExit("work confirmation blocked: missing export meta")
|
|
282
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
283
|
-
payload["workSha256"] = file_sha256(work_path)
|
|
284
|
-
payload["workConfirmedAt"] = utc_now_iso()
|
|
285
|
-
payload["workConfirmedBy"] = actor
|
|
286
|
-
payload["status"] = "work_confirmed"
|
|
287
|
-
save_meta(meta_path, payload)
|
|
288
|
-
return payload
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
def update_build_meta(
|
|
292
|
-
meta_path: Path,
|
|
293
|
-
*,
|
|
294
|
-
work_path: Path,
|
|
295
|
-
submit_path: Path,
|
|
296
|
-
contract_path: Path,
|
|
297
|
-
validation: Dict[str, Any],
|
|
298
|
-
) -> Dict[str, Any]:
|
|
299
|
-
raw = load_meta(meta_path)
|
|
300
|
-
if not raw:
|
|
301
|
-
raise SystemExit("submit build blocked: missing export meta")
|
|
302
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
303
|
-
current_work_sha = file_sha256(work_path)
|
|
304
|
-
previous_work_sha = payload.get("workSha256")
|
|
305
|
-
payload["workSha256"] = current_work_sha
|
|
306
|
-
payload["submitSha256"] = file_sha256(submit_path)
|
|
307
|
-
payload["contractSha256"] = file_sha256(contract_path)
|
|
308
|
-
payload["submitBuiltAt"] = utc_now_iso()
|
|
309
|
-
payload["validation"] = validation
|
|
310
|
-
payload["lintPassed"] = bool(validation.get("ok"))
|
|
311
|
-
payload["lintSha256"] = payload["submitSha256"]
|
|
312
|
-
if previous_work_sha and previous_work_sha != current_work_sha:
|
|
313
|
-
payload["workConfirmedAt"] = None
|
|
314
|
-
payload["workConfirmedBy"] = None
|
|
315
|
-
payload["submitConfirmedAt"] = None
|
|
316
|
-
payload["submitConfirmedBy"] = None
|
|
317
|
-
payload["status"] = "submit_built"
|
|
318
|
-
save_meta(meta_path, payload)
|
|
319
|
-
return payload
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
def record_submit_confirmation(meta_path: Path, *, actor: str, submit_path: Path) -> Dict[str, Any]:
|
|
323
|
-
raw = load_meta(meta_path)
|
|
324
|
-
if not raw:
|
|
325
|
-
raise SystemExit("submit confirmation blocked: missing meta")
|
|
326
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
327
|
-
if payload.get("status") != "submit_built":
|
|
328
|
-
raise SystemExit(f"submit confirmation blocked: current status is {payload.get('status')}, expected submit_built")
|
|
329
|
-
payload["submitSha256"] = file_sha256(submit_path)
|
|
330
|
-
payload["submitConfirmedAt"] = utc_now_iso()
|
|
331
|
-
payload["submitConfirmedBy"] = actor
|
|
332
|
-
payload["status"] = "submit_confirmed"
|
|
333
|
-
save_meta(meta_path, payload)
|
|
334
|
-
return payload
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
def ensure_submission_allowed(meta_path: Path, work_path: Path, submit_path: Path, contract_path: Path) -> Dict[str, Any]:
|
|
338
|
-
raw = load_meta(meta_path)
|
|
339
|
-
if not raw:
|
|
340
|
-
raise SystemExit("submission blocked: missing meta")
|
|
341
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
342
|
-
if payload.get("status") != "submit_confirmed":
|
|
343
|
-
raise SystemExit(f"submission blocked: current status is {payload.get('status')}, expected submit_confirmed")
|
|
344
|
-
if not payload.get("workConfirmedAt"):
|
|
345
|
-
raise SystemExit("submission blocked: work was not confirmed")
|
|
346
|
-
if not payload.get("submitBuiltAt"):
|
|
347
|
-
raise SystemExit("submission blocked: submit payload has not been built")
|
|
348
|
-
if not payload.get("submitConfirmedAt"):
|
|
349
|
-
raise SystemExit("submission blocked: submit payload was not confirmed")
|
|
350
|
-
if payload.get("workSha256") != file_sha256(work_path):
|
|
351
|
-
raise SystemExit("submission blocked: work file changed after confirmation")
|
|
352
|
-
if payload.get("submitSha256") != file_sha256(submit_path):
|
|
353
|
-
raise SystemExit("submission blocked: submit payload changed after confirmation")
|
|
354
|
-
if payload.get("contractSha256") != file_sha256(contract_path):
|
|
355
|
-
raise SystemExit("submission blocked: contract file changed after submit build")
|
|
356
|
-
if payload.get("lintPassed") is not True:
|
|
357
|
-
raise SystemExit("submission blocked: build validation did not pass")
|
|
358
|
-
return payload
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
def persist_submission_meta(
|
|
362
|
-
meta_path: Path,
|
|
363
|
-
*,
|
|
364
|
-
remote_id: Any | None,
|
|
365
|
-
remote_guid: str | None,
|
|
366
|
-
verification: Dict[str, Any],
|
|
367
|
-
status: str,
|
|
368
|
-
) -> Dict[str, Any]:
|
|
369
|
-
raw = load_meta(meta_path)
|
|
370
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
371
|
-
payload["remoteId"] = remote_id
|
|
372
|
-
payload["remoteGuid"] = remote_guid
|
|
373
|
-
payload["submittedAt"] = utc_now_iso()
|
|
374
|
-
payload["verification"] = verification
|
|
375
|
-
payload["status"] = status
|
|
376
|
-
save_meta(meta_path, payload)
|
|
377
|
-
return payload
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
def persist_doc_debug_result(
|
|
381
|
-
meta_path: Path,
|
|
382
|
-
*,
|
|
383
|
-
accepted: bool,
|
|
384
|
-
acceptance_path: Path,
|
|
385
|
-
) -> Dict[str, Any]:
|
|
386
|
-
raw = load_meta(meta_path)
|
|
387
|
-
payload = ensure_meta_shape(raw, stem=str(raw["stem"]), layer=str(raw["layer"]), mode=str(raw["mode"]))
|
|
388
|
-
payload["runtimeAcceptance"]["recordedAt"] = utc_now_iso()
|
|
389
|
-
payload["runtimeAcceptance"]["result"] = "passed" if accepted else "failed"
|
|
390
|
-
payload["runtimeAcceptance"]["acceptancePath"] = str(acceptance_path)
|
|
391
|
-
payload["status"] = "completed" if accepted else "manual_followup_required"
|
|
392
|
-
save_meta(meta_path, payload)
|
|
393
|
-
return payload
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
def extract_api_data(payload: Any) -> Any:
|
|
397
|
-
if isinstance(payload, dict) and "data" in payload:
|
|
398
|
-
return payload.get("data")
|
|
399
|
-
return payload
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
def extract_records(payload: Any) -> list[Any]:
|
|
403
|
-
data = extract_api_data(payload)
|
|
404
|
-
if isinstance(data, list):
|
|
405
|
-
return data
|
|
406
|
-
if isinstance(data, dict):
|
|
407
|
-
for key in ("list", "rows", "items", "records", "result"):
|
|
408
|
-
value = data.get(key)
|
|
409
|
-
if isinstance(value, list):
|
|
410
|
-
return value
|
|
411
|
-
return [data]
|
|
412
|
-
return []
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
def extract_first_record(payload: Any) -> Dict[str, Any]:
|
|
416
|
-
records = extract_records(payload)
|
|
417
|
-
if not records:
|
|
418
|
-
return {}
|
|
419
|
-
first = records[0]
|
|
420
|
-
return first if isinstance(first, dict) else {}
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
def _normalize_json_like(value: Any) -> Any:
|
|
424
|
-
if isinstance(value, str):
|
|
425
|
-
text = value.strip()
|
|
426
|
-
if text.startswith("{") or text.startswith("[") or (text.startswith('"') and text.endswith('"')):
|
|
427
|
-
try:
|
|
428
|
-
return json.loads(text)
|
|
429
|
-
except json.JSONDecodeError:
|
|
430
|
-
return value
|
|
431
|
-
return value
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
def _normalize_headers(headers: Mapping[str, Any] | None) -> Dict[str, str]:
|
|
435
|
-
result: Dict[str, str] = {}
|
|
436
|
-
if not headers:
|
|
437
|
-
return result
|
|
438
|
-
for key, value in headers.items():
|
|
439
|
-
lower = str(key).strip().lower()
|
|
440
|
-
if lower in CONTRACT_HEADER_WHITELIST and value not in (None, ""):
|
|
441
|
-
result[lower] = str(value)
|
|
442
|
-
return result
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
def _parse_query(url: str) -> tuple[str, str, Dict[str, str]]:
|
|
446
|
-
parsed = urllib.parse.urlparse(url)
|
|
447
|
-
query = {key: value for key, value in urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)}
|
|
448
|
-
path = parsed.path or "/"
|
|
449
|
-
origin = f"{parsed.scheme}://{parsed.netloc}"
|
|
450
|
-
return origin, path, query
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
def _infer_payload_path(body: Any) -> list[str]:
|
|
454
|
-
if isinstance(body, dict):
|
|
455
|
-
for key in ("data", "payload", "item", "params"):
|
|
456
|
-
if key in body and isinstance(body[key], (dict, list)):
|
|
457
|
-
return [key]
|
|
458
|
-
return []
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
def _normalize_body(value: Any) -> tuple[Any, str]:
|
|
462
|
-
if value in (None, ""):
|
|
463
|
-
return None, "none"
|
|
464
|
-
if isinstance(value, (dict, list)):
|
|
465
|
-
return value, "json"
|
|
466
|
-
if isinstance(value, str):
|
|
467
|
-
text = value.strip()
|
|
468
|
-
if not text:
|
|
469
|
-
return None, "none"
|
|
470
|
-
try:
|
|
471
|
-
return json.loads(text), "json"
|
|
472
|
-
except json.JSONDecodeError:
|
|
473
|
-
return value, "text"
|
|
474
|
-
return value, "raw"
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
def _parse_fetch_capture(text: str) -> Dict[str, Any] | None:
|
|
478
|
-
match = re.search(r"fetch\(\s*(?P<url>\".*?\"|'.*?')\s*,\s*(?P<options>\{.*\})\s*\)\s*;?\s*$", text, re.S)
|
|
479
|
-
if not match:
|
|
480
|
-
return None
|
|
481
|
-
url = ast.literal_eval(match.group("url"))
|
|
482
|
-
options_text = match.group("options")
|
|
483
|
-
try:
|
|
484
|
-
options = json.loads(options_text)
|
|
485
|
-
except json.JSONDecodeError:
|
|
486
|
-
options = ast.literal_eval(options_text)
|
|
487
|
-
if not isinstance(options, dict):
|
|
488
|
-
raise SystemExit("fetch capture options must be an object")
|
|
489
|
-
headers = _normalize_headers(options.get("headers") if isinstance(options.get("headers"), dict) else {})
|
|
490
|
-
body, body_kind = _normalize_body(options.get("body"))
|
|
491
|
-
origin, path, query = _parse_query(url)
|
|
492
|
-
return {
|
|
493
|
-
"sourceType": "fetch",
|
|
494
|
-
"method": str(options.get("method") or ("POST" if body_kind != "none" else "GET")).upper(),
|
|
495
|
-
"capturedUrl": url,
|
|
496
|
-
"origin": origin,
|
|
497
|
-
"path": path,
|
|
498
|
-
"query": query,
|
|
499
|
-
"headers": headers,
|
|
500
|
-
"bodyTemplate": body,
|
|
501
|
-
"bodyKind": body_kind,
|
|
502
|
-
"payloadPath": _infer_payload_path(body),
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
def _parse_curl_capture(text: str) -> Dict[str, Any] | None:
|
|
507
|
-
stripped = text.strip()
|
|
508
|
-
if not stripped.startswith("curl "):
|
|
509
|
-
return None
|
|
510
|
-
tokens = shlex.split(stripped)
|
|
511
|
-
method = "GET"
|
|
512
|
-
url = ""
|
|
513
|
-
headers: Dict[str, str] = {}
|
|
514
|
-
body_value: Any = None
|
|
515
|
-
idx = 1
|
|
516
|
-
while idx < len(tokens):
|
|
517
|
-
token = tokens[idx]
|
|
518
|
-
if token in {"-X", "--request"} and idx + 1 < len(tokens):
|
|
519
|
-
method = tokens[idx + 1].upper()
|
|
520
|
-
idx += 2
|
|
521
|
-
continue
|
|
522
|
-
if token in {"-H", "--header"} and idx + 1 < len(tokens):
|
|
523
|
-
header_value = tokens[idx + 1]
|
|
524
|
-
if ":" in header_value:
|
|
525
|
-
key, value = header_value.split(":", 1)
|
|
526
|
-
headers[key.strip()] = value.strip()
|
|
527
|
-
idx += 2
|
|
528
|
-
continue
|
|
529
|
-
if token in {"--data", "--data-raw", "--data-binary", "-d"} and idx + 1 < len(tokens):
|
|
530
|
-
body_value = tokens[idx + 1]
|
|
531
|
-
idx += 2
|
|
532
|
-
if method == "GET":
|
|
533
|
-
method = "POST"
|
|
534
|
-
continue
|
|
535
|
-
if token.startswith("http://") or token.startswith("https://"):
|
|
536
|
-
url = token
|
|
537
|
-
idx += 1
|
|
538
|
-
if not url:
|
|
539
|
-
raise SystemExit("curl capture missing url")
|
|
540
|
-
headers = _normalize_headers(headers)
|
|
541
|
-
body, body_kind = _normalize_body(body_value)
|
|
542
|
-
origin, path, query = _parse_query(url)
|
|
543
|
-
return {
|
|
544
|
-
"sourceType": "curl",
|
|
545
|
-
"method": method,
|
|
546
|
-
"capturedUrl": url,
|
|
547
|
-
"origin": origin,
|
|
548
|
-
"path": path,
|
|
549
|
-
"query": query,
|
|
550
|
-
"headers": headers,
|
|
551
|
-
"bodyTemplate": body,
|
|
552
|
-
"bodyKind": body_kind,
|
|
553
|
-
"payloadPath": _infer_payload_path(body),
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
def _pick_har_entry(entries: Sequence[Dict[str, Any]], *, preferred_substring: str | None = None) -> Dict[str, Any]:
|
|
558
|
-
if preferred_substring:
|
|
559
|
-
for entry in reversed(entries):
|
|
560
|
-
request = entry.get("request") if isinstance(entry, dict) else None
|
|
561
|
-
url = request.get("url") if isinstance(request, dict) else ""
|
|
562
|
-
if preferred_substring in str(url):
|
|
563
|
-
return entry
|
|
564
|
-
if not entries:
|
|
565
|
-
raise SystemExit("HAR capture contains no entries")
|
|
566
|
-
return entries[-1]
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
def _parse_har_capture(text: str, *, preferred_substring: str | None = None) -> Dict[str, Any] | None:
|
|
570
|
-
try:
|
|
571
|
-
payload = json.loads(text)
|
|
572
|
-
except json.JSONDecodeError:
|
|
573
|
-
return None
|
|
574
|
-
if not isinstance(payload, dict) or "log" not in payload:
|
|
575
|
-
return None
|
|
576
|
-
entries = payload.get("log", {}).get("entries", [])
|
|
577
|
-
if not isinstance(entries, list):
|
|
578
|
-
raise SystemExit("HAR capture log.entries must be an array")
|
|
579
|
-
entry = _pick_har_entry([item for item in entries if isinstance(item, dict)], preferred_substring=preferred_substring)
|
|
580
|
-
request = entry.get("request")
|
|
581
|
-
if not isinstance(request, dict):
|
|
582
|
-
raise SystemExit("HAR entry missing request")
|
|
583
|
-
headers = _normalize_headers({item.get("name"): item.get("value") for item in request.get("headers", []) if isinstance(item, dict)})
|
|
584
|
-
post_data = request.get("postData")
|
|
585
|
-
body, body_kind = _normalize_body(post_data.get("text") if isinstance(post_data, dict) else None)
|
|
586
|
-
url = str(request.get("url") or "")
|
|
587
|
-
origin, path, query = _parse_query(url)
|
|
588
|
-
return {
|
|
589
|
-
"sourceType": "har",
|
|
590
|
-
"method": str(request.get("method") or "GET").upper(),
|
|
591
|
-
"capturedUrl": url,
|
|
592
|
-
"origin": origin,
|
|
593
|
-
"path": path,
|
|
594
|
-
"query": query,
|
|
595
|
-
"headers": headers,
|
|
596
|
-
"bodyTemplate": body,
|
|
597
|
-
"bodyKind": body_kind,
|
|
598
|
-
"payloadPath": _infer_payload_path(body),
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
def _parse_json_request_object(text: str) -> Dict[str, Any] | None:
|
|
603
|
-
try:
|
|
604
|
-
payload = json.loads(text)
|
|
605
|
-
except json.JSONDecodeError:
|
|
606
|
-
return None
|
|
607
|
-
if not isinstance(payload, dict) or "url" not in payload or "method" not in payload:
|
|
608
|
-
return None
|
|
609
|
-
headers = _normalize_headers(payload.get("headers") if isinstance(payload.get("headers"), dict) else {})
|
|
610
|
-
body, body_kind = _normalize_body(payload.get("body"))
|
|
611
|
-
origin, path, query = _parse_query(str(payload["url"]))
|
|
612
|
-
return {
|
|
613
|
-
"sourceType": "json",
|
|
614
|
-
"method": str(payload.get("method") or "GET").upper(),
|
|
615
|
-
"capturedUrl": str(payload["url"]),
|
|
616
|
-
"origin": origin,
|
|
617
|
-
"path": path,
|
|
618
|
-
"query": query,
|
|
619
|
-
"headers": headers,
|
|
620
|
-
"bodyTemplate": body,
|
|
621
|
-
"bodyKind": body_kind,
|
|
622
|
-
"payloadPath": _infer_payload_path(body),
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
def default_contract_preferred_path(layer: str, *, binding: bool = False) -> str | None:
|
|
627
|
-
if binding:
|
|
628
|
-
return "/api/api_proxy_entity_binding"
|
|
629
|
-
return {
|
|
630
|
-
"platform": "/api/api_platform",
|
|
631
|
-
"instance": "/api/api_platform_instance",
|
|
632
|
-
"api": "/api/api_proxy",
|
|
633
|
-
}.get(layer)
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
def normalize_request_capture(text: str, *, layer: str, preferred_substring: str | None = None) -> Dict[str, Any]:
|
|
637
|
-
preferred = preferred_substring or default_contract_preferred_path(layer)
|
|
638
|
-
for parser in (
|
|
639
|
-
lambda source: _parse_fetch_capture(source),
|
|
640
|
-
lambda source: _parse_curl_capture(source),
|
|
641
|
-
lambda source: _parse_har_capture(source, preferred_substring=preferred),
|
|
642
|
-
lambda source: _parse_json_request_object(source),
|
|
643
|
-
):
|
|
644
|
-
result = parser(text)
|
|
645
|
-
if result:
|
|
646
|
-
return result
|
|
647
|
-
raise SystemExit("unsupported capture format: expected fetch/curl/HAR/JSON request object")
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
def build_write_contract(
|
|
651
|
-
*,
|
|
652
|
-
layer: str,
|
|
653
|
-
mode: str,
|
|
654
|
-
primary_capture_text: str,
|
|
655
|
-
binding_capture_text: str | None = None,
|
|
656
|
-
primary_match: str | None = None,
|
|
657
|
-
binding_match: str | None = None,
|
|
658
|
-
) -> Dict[str, Any]:
|
|
659
|
-
if layer not in VALID_LAYERS - {"doc-debug"}:
|
|
660
|
-
raise SystemExit(f"unsupported write-contract layer: {layer}")
|
|
661
|
-
if mode not in VALID_MODES:
|
|
662
|
-
raise SystemExit(f"unsupported mode: {mode}")
|
|
663
|
-
contract: Dict[str, Any] = {
|
|
664
|
-
"layer": layer,
|
|
665
|
-
"mode": mode,
|
|
666
|
-
"capturedAt": utc_now_iso(),
|
|
667
|
-
"requests": {
|
|
668
|
-
"primary": normalize_request_capture(primary_capture_text, layer=layer, preferred_substring=primary_match),
|
|
669
|
-
},
|
|
670
|
-
}
|
|
671
|
-
if binding_capture_text:
|
|
672
|
-
contract["requests"]["binding"] = normalize_request_capture(
|
|
673
|
-
binding_capture_text,
|
|
674
|
-
layer="api",
|
|
675
|
-
preferred_substring=binding_match or default_contract_preferred_path("api", binding=True),
|
|
676
|
-
)
|
|
677
|
-
return contract
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
def _drop_identity_keys(payload: Mapping[str, Any]) -> Dict[str, Any]:
|
|
681
|
-
return {key: copy.deepcopy(value) for key, value in payload.items() if key not in DROP_IDENTITY_KEYS}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
def _fragment_dir(stem: str) -> Path:
|
|
685
|
-
path = paths_for(stem)["fragments"]
|
|
686
|
-
path.mkdir(parents=True, exist_ok=True)
|
|
687
|
-
return path
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
def platform_detail_to_work(detail: Dict[str, Any], *, mode: str) -> Dict[str, Any]:
|
|
691
|
-
source = _drop_identity_keys(detail) if mode == "create" else copy.deepcopy(detail)
|
|
692
|
-
return {
|
|
693
|
-
"id": detail.get("id") if mode == "update" else None,
|
|
694
|
-
"mode": mode,
|
|
695
|
-
"layer": "platform",
|
|
696
|
-
"basic": {
|
|
697
|
-
"name": source.get("name", ""),
|
|
698
|
-
"platform_key": source.get("platform_key", ""),
|
|
699
|
-
"category": source.get("category", ""),
|
|
700
|
-
"description": source.get("description", ""),
|
|
701
|
-
"icon": source.get("icon", ""),
|
|
702
|
-
"status": source.get("status", 1),
|
|
703
|
-
},
|
|
704
|
-
"preserve": {
|
|
705
|
-
"guid": detail.get("guid"),
|
|
706
|
-
"rawKeys": sorted(detail.keys()),
|
|
707
|
-
},
|
|
708
|
-
"notes": "",
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
def instance_detail_to_work(detail: Dict[str, Any], *, mode: str, stem: str) -> Dict[str, Any]:
|
|
713
|
-
source = _drop_identity_keys(detail) if mode == "create" else copy.deepcopy(detail)
|
|
714
|
-
fragments_dir = _fragment_dir(stem)
|
|
715
|
-
script_files: Dict[str, str] = {}
|
|
716
|
-
for name in SCRIPT_FIELD_NAMES:
|
|
717
|
-
path = fragments_dir / f"{name}.js"
|
|
718
|
-
path.write_text(str(source.get(name) or ""), encoding="utf-8")
|
|
719
|
-
script_files[name] = str(path)
|
|
720
|
-
return {
|
|
721
|
-
"id": detail.get("id") if mode == "update" else None,
|
|
722
|
-
"mode": mode,
|
|
723
|
-
"layer": "instance",
|
|
724
|
-
"basic": {
|
|
725
|
-
"name": source.get("name", ""),
|
|
726
|
-
"instance_key": source.get("instance_key", ""),
|
|
727
|
-
"env_type": source.get("env_type", ""),
|
|
728
|
-
"auth_type": source.get("auth_type", ""),
|
|
729
|
-
"description": source.get("description", ""),
|
|
730
|
-
"status": source.get("status", 1),
|
|
731
|
-
"api_platform_guid": source.get("api_platform_guid", detail.get("api_platform_guid", "")),
|
|
732
|
-
},
|
|
733
|
-
"config_schema": copy.deepcopy(source.get("config_schema") or {}),
|
|
734
|
-
"scriptFiles": script_files,
|
|
735
|
-
"preserve": {
|
|
736
|
-
"guid": detail.get("guid"),
|
|
737
|
-
"rawKeys": sorted(detail.keys()),
|
|
738
|
-
},
|
|
739
|
-
"notes": "",
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
def api_detail_to_work(api_detail: Dict[str, Any], *, binding: Dict[str, Any] | None, mode: str, stem: str) -> Dict[str, Any]:
|
|
744
|
-
source = _drop_identity_keys(api_detail) if mode == "create" else copy.deepcopy(api_detail)
|
|
745
|
-
binding_source = _drop_identity_keys(binding or {}) if mode == "create" else copy.deepcopy(binding or {})
|
|
746
|
-
fragments_dir = _fragment_dir(stem)
|
|
747
|
-
sidecar_files: Dict[str, str] = {}
|
|
748
|
-
for name in API_SIDECAR_NAMES:
|
|
749
|
-
path = fragments_dir / f"{name}.json"
|
|
750
|
-
if name == "response_binding":
|
|
751
|
-
payload = binding_source
|
|
752
|
-
else:
|
|
753
|
-
payload = _normalize_json_like(source.get(name))
|
|
754
|
-
dump_json(path, payload)
|
|
755
|
-
sidecar_files[name] = str(path)
|
|
756
|
-
return {
|
|
757
|
-
"id": api_detail.get("id") if mode == "update" else None,
|
|
758
|
-
"mode": mode,
|
|
759
|
-
"layer": "api",
|
|
760
|
-
"basic": {
|
|
761
|
-
"name": source.get("name", ""),
|
|
762
|
-
"api_key": source.get("api_key", ""),
|
|
763
|
-
"status": source.get("status", 1),
|
|
764
|
-
"version": source.get("version", 1),
|
|
765
|
-
"method": source.get("method", ""),
|
|
766
|
-
"path": source.get("path", ""),
|
|
767
|
-
"description": source.get("description", ""),
|
|
768
|
-
"api_platform_guid": source.get("api_platform_guid", api_detail.get("api_platform_guid", "")),
|
|
769
|
-
},
|
|
770
|
-
"sidecarFiles": sidecar_files,
|
|
771
|
-
"preserve": {
|
|
772
|
-
"guid": api_detail.get("guid"),
|
|
773
|
-
"rawKeys": sorted(api_detail.keys()),
|
|
774
|
-
},
|
|
775
|
-
"notes": "",
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
def doc_debug_context_to_work(
|
|
780
|
-
*,
|
|
781
|
-
workspace: str,
|
|
782
|
-
platform_key: str,
|
|
783
|
-
api_id: Any,
|
|
784
|
-
api_key: str,
|
|
785
|
-
base_url: str,
|
|
786
|
-
instance_candidates: Sequence[Dict[str, Any]],
|
|
787
|
-
) -> Dict[str, Any]:
|
|
788
|
-
return {
|
|
789
|
-
"layer": "doc-debug",
|
|
790
|
-
"mode": "update",
|
|
791
|
-
"workspace": workspace,
|
|
792
|
-
"platform_key": platform_key,
|
|
793
|
-
"api_id": api_id,
|
|
794
|
-
"api_key": api_key,
|
|
795
|
-
"doc_url": f"{base_url}/w:{workspace}/api-docs/system_api/{api_id}?system={platform_key}",
|
|
796
|
-
"instance_candidates": list(instance_candidates),
|
|
797
|
-
"api_args": [],
|
|
798
|
-
"response_summary": "",
|
|
799
|
-
"matched_expected": None,
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
def _read_script_file(path: str) -> str:
|
|
804
|
-
return Path(path).read_text(encoding="utf-8")
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
def _load_sidecar(path: str) -> Any:
|
|
808
|
-
return load_json(Path(path))
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
def _validate_platform_work(work: Dict[str, Any]) -> list[str]:
|
|
812
|
-
errors: list[str] = []
|
|
813
|
-
basic = work.get("basic") if isinstance(work.get("basic"), dict) else {}
|
|
814
|
-
for key in ("name", "platform_key"):
|
|
815
|
-
if not str(basic.get(key) or "").strip():
|
|
816
|
-
errors.append(f"platform.basic.{key} is required")
|
|
817
|
-
return errors
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
def _validate_instance_work(work: Dict[str, Any]) -> list[str]:
|
|
821
|
-
errors: list[str] = []
|
|
822
|
-
basic = work.get("basic") if isinstance(work.get("basic"), dict) else {}
|
|
823
|
-
for key in ("name", "instance_key"):
|
|
824
|
-
if not str(basic.get(key) or "").strip():
|
|
825
|
-
errors.append(f"instance.basic.{key} is required")
|
|
826
|
-
config_schema = work.get("config_schema")
|
|
827
|
-
if not isinstance(config_schema, dict):
|
|
828
|
-
errors.append("instance.config_schema must be an object")
|
|
829
|
-
for field, path in (work.get("scriptFiles") or {}).items():
|
|
830
|
-
if field not in SCRIPT_FIELD_NAMES:
|
|
831
|
-
errors.append(f"unknown instance script field: {field}")
|
|
832
|
-
if not Path(path).exists():
|
|
833
|
-
errors.append(f"missing script fragment: {path}")
|
|
834
|
-
return errors
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
def _validate_api_work(work: Dict[str, Any], contract: Dict[str, Any] | None = None) -> list[str]:
|
|
838
|
-
errors: list[str] = []
|
|
839
|
-
basic = work.get("basic") if isinstance(work.get("basic"), dict) else {}
|
|
840
|
-
for key in ("name", "api_key", "method", "path"):
|
|
841
|
-
if not str(basic.get(key) or "").strip():
|
|
842
|
-
errors.append(f"api.basic.{key} is required")
|
|
843
|
-
sidecars = work.get("sidecarFiles") if isinstance(work.get("sidecarFiles"), dict) else {}
|
|
844
|
-
for name in API_SIDECAR_NAMES:
|
|
845
|
-
if name not in sidecars:
|
|
846
|
-
errors.append(f"missing api sidecar file ref: {name}")
|
|
847
|
-
continue
|
|
848
|
-
if not Path(sidecars[name]).exists():
|
|
849
|
-
errors.append(f"missing api sidecar file: {sidecars[name]}")
|
|
850
|
-
if errors:
|
|
851
|
-
return errors
|
|
852
|
-
binding_payload = _load_sidecar(sidecars["response_binding"])
|
|
853
|
-
if binding_payload:
|
|
854
|
-
if not isinstance(binding_payload, dict):
|
|
855
|
-
errors.append("response_binding sidecar must be an object")
|
|
856
|
-
else:
|
|
857
|
-
if not any(key in binding_payload for key in ("entity_id", "entity", "target_entity_id")):
|
|
858
|
-
errors.append("response_binding sidecar must include target entity information")
|
|
859
|
-
if contract and not isinstance((contract.get("requests") or {}).get("binding"), dict):
|
|
860
|
-
errors.append("api layer with response_binding requires a captured binding write contract")
|
|
861
|
-
return errors
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
def build_submit_bundle(work: Dict[str, Any], *, contract: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
|
865
|
-
layer = str(work.get("layer") or "")
|
|
866
|
-
mode = str(work.get("mode") or "update")
|
|
867
|
-
if layer not in VALID_LAYERS - {"doc-debug"}:
|
|
868
|
-
raise SystemExit(f"unsupported build layer: {layer}")
|
|
869
|
-
if mode not in VALID_MODES:
|
|
870
|
-
raise SystemExit(f"unsupported build mode: {mode}")
|
|
871
|
-
|
|
872
|
-
if layer == "platform":
|
|
873
|
-
errors = _validate_platform_work(work)
|
|
874
|
-
payload = copy.deepcopy(work.get("basic") or {})
|
|
875
|
-
execution_plan = ["platform", "readback"]
|
|
876
|
-
binding_payload = None
|
|
877
|
-
elif layer == "instance":
|
|
878
|
-
errors = _validate_instance_work(work)
|
|
879
|
-
scripts = {field: _read_script_file(path) for field, path in (work.get("scriptFiles") or {}).items()}
|
|
880
|
-
payload = copy.deepcopy(work.get("basic") or {})
|
|
881
|
-
payload["config_schema"] = copy.deepcopy(work.get("config_schema") or {})
|
|
882
|
-
payload.update(scripts)
|
|
883
|
-
execution_plan = ["instance", "readback"]
|
|
884
|
-
binding_payload = None
|
|
885
|
-
else:
|
|
886
|
-
errors = _validate_api_work(work, contract=contract)
|
|
887
|
-
basic = copy.deepcopy(work.get("basic") or {})
|
|
888
|
-
sidecars = work.get("sidecarFiles") or {}
|
|
889
|
-
payload = {
|
|
890
|
-
**basic,
|
|
891
|
-
"request_schema": _load_sidecar(sidecars["request_schema"]),
|
|
892
|
-
"response_schema": _load_sidecar(sidecars["response_schema"]),
|
|
893
|
-
"request_example": _load_sidecar(sidecars["request_example"]),
|
|
894
|
-
"response_example": _load_sidecar(sidecars["response_example"]),
|
|
895
|
-
}
|
|
896
|
-
binding_payload = _load_sidecar(sidecars["response_binding"])
|
|
897
|
-
execution_plan = ["api_proxy"]
|
|
898
|
-
if binding_payload:
|
|
899
|
-
execution_plan.append("binding")
|
|
900
|
-
execution_plan.append("readback")
|
|
901
|
-
|
|
902
|
-
if errors:
|
|
903
|
-
raise SystemExit("; ".join(errors))
|
|
904
|
-
|
|
905
|
-
bundle = {
|
|
906
|
-
"layer": layer,
|
|
907
|
-
"mode": mode,
|
|
908
|
-
"payload": payload,
|
|
909
|
-
"response_binding": binding_payload,
|
|
910
|
-
"executionPlan": execution_plan,
|
|
911
|
-
"validation": {"ok": True, "errors": [], "warnings": []},
|
|
912
|
-
}
|
|
913
|
-
return bundle
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
def _merge_overlay(target: Any, overlay: Any) -> Any:
|
|
917
|
-
if isinstance(target, dict) and isinstance(overlay, dict):
|
|
918
|
-
merged = copy.deepcopy(target)
|
|
919
|
-
for key, value in overlay.items():
|
|
920
|
-
merged[key] = copy.deepcopy(value)
|
|
921
|
-
return merged
|
|
922
|
-
return copy.deepcopy(overlay)
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
def _set_nested_value(target: Any, path: Sequence[str], value: Any) -> Any:
|
|
926
|
-
if not path:
|
|
927
|
-
return _merge_overlay(target, value)
|
|
928
|
-
current = copy.deepcopy(target) if isinstance(target, dict) else {}
|
|
929
|
-
cursor = current
|
|
930
|
-
for key in path[:-1]:
|
|
931
|
-
next_value = cursor.get(key)
|
|
932
|
-
if not isinstance(next_value, dict):
|
|
933
|
-
next_value = {}
|
|
934
|
-
cursor[key] = next_value
|
|
935
|
-
cursor = next_value
|
|
936
|
-
cursor[path[-1]] = copy.deepcopy(value)
|
|
937
|
-
return current
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
def materialize_contract_body(request_contract: Dict[str, Any], submit_payload: Any) -> Any:
|
|
941
|
-
template = copy.deepcopy(request_contract.get("bodyTemplate"))
|
|
942
|
-
path = list(request_contract.get("payloadPath") or [])
|
|
943
|
-
if template is None and not path:
|
|
944
|
-
return copy.deepcopy(submit_payload)
|
|
945
|
-
if request_contract.get("bodyKind") == "text":
|
|
946
|
-
return submit_payload if isinstance(submit_payload, str) else json.dumps(submit_payload, ensure_ascii=False)
|
|
947
|
-
return _set_nested_value(template, path, submit_payload)
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
def normalize_for_compare(value: Any) -> Any:
|
|
951
|
-
normalized = _normalize_json_like(value)
|
|
952
|
-
if isinstance(normalized, dict):
|
|
953
|
-
return {key: normalize_for_compare(item) for key, item in sorted(normalized.items())}
|
|
954
|
-
if isinstance(normalized, list):
|
|
955
|
-
return [normalize_for_compare(item) for item in normalized]
|
|
956
|
-
return normalized
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
def _canonicalize_binding_payload(value: Any) -> Any:
|
|
960
|
-
normalized = _normalize_json_like(value)
|
|
961
|
-
if not isinstance(normalized, dict):
|
|
962
|
-
return normalize_for_compare(normalized)
|
|
963
|
-
result: Dict[str, Any] = {}
|
|
964
|
-
entity_value = None
|
|
965
|
-
for key in ("entity_id", "target_entity_id", "entity"):
|
|
966
|
-
if normalized.get(key) not in (None, ""):
|
|
967
|
-
entity_value = normalized.get(key)
|
|
968
|
-
break
|
|
969
|
-
if entity_value not in (None, ""):
|
|
970
|
-
result["entity_id"] = entity_value
|
|
971
|
-
|
|
972
|
-
direction_value = normalized.get("direction") or normalized.get("q_direction")
|
|
973
|
-
if direction_value not in (None, ""):
|
|
974
|
-
result["direction"] = direction_value
|
|
975
|
-
|
|
976
|
-
proxy_guid = normalized.get("q_proxy_guid") or normalized.get("proxy_guid") or normalized.get("api_proxy_guid")
|
|
977
|
-
if proxy_guid not in (None, ""):
|
|
978
|
-
result["proxy_guid"] = proxy_guid
|
|
979
|
-
|
|
980
|
-
for key, item in normalized.items():
|
|
981
|
-
if key in {
|
|
982
|
-
"entity_id",
|
|
983
|
-
"target_entity_id",
|
|
984
|
-
"entity",
|
|
985
|
-
"direction",
|
|
986
|
-
"q_direction",
|
|
987
|
-
"q_proxy_guid",
|
|
988
|
-
"proxy_guid",
|
|
989
|
-
"api_proxy_guid",
|
|
990
|
-
"proxy_id",
|
|
991
|
-
"api_proxy_id",
|
|
992
|
-
}:
|
|
993
|
-
continue
|
|
994
|
-
result[key] = item
|
|
995
|
-
return normalize_for_compare(result)
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
def summarize_verification(*, layer: str, submit_bundle: Dict[str, Any], readback: Dict[str, Any]) -> Dict[str, Any]:
|
|
999
|
-
payload = submit_bundle.get("payload") if isinstance(submit_bundle.get("payload"), dict) else {}
|
|
1000
|
-
binding_payload = submit_bundle.get("response_binding")
|
|
1001
|
-
mismatches: list[Dict[str, Any]] = []
|
|
1002
|
-
|
|
1003
|
-
if layer == "platform":
|
|
1004
|
-
expected = payload
|
|
1005
|
-
actual = {key: readback.get(key) for key in expected}
|
|
1006
|
-
elif layer == "instance":
|
|
1007
|
-
expected = payload
|
|
1008
|
-
actual = {key: readback.get(key) for key in expected}
|
|
1009
|
-
else:
|
|
1010
|
-
expected = payload
|
|
1011
|
-
actual = {key: readback.get("api", {}).get(key) for key in expected}
|
|
1012
|
-
if binding_payload is not None:
|
|
1013
|
-
actual_binding = readback.get("response_binding") or {}
|
|
1014
|
-
if _canonicalize_binding_payload(binding_payload) != _canonicalize_binding_payload(actual_binding):
|
|
1015
|
-
mismatches.append(
|
|
1016
|
-
{
|
|
1017
|
-
"field": "response_binding",
|
|
1018
|
-
"expected": _canonicalize_binding_payload(binding_payload),
|
|
1019
|
-
"actual": _canonicalize_binding_payload(actual_binding),
|
|
1020
|
-
}
|
|
1021
|
-
)
|
|
1022
|
-
|
|
1023
|
-
for key, expected_value in expected.items():
|
|
1024
|
-
actual_value = actual.get(key)
|
|
1025
|
-
if normalize_for_compare(expected_value) != normalize_for_compare(actual_value):
|
|
1026
|
-
mismatches.append(
|
|
1027
|
-
{
|
|
1028
|
-
"field": key,
|
|
1029
|
-
"expected": normalize_for_compare(expected_value),
|
|
1030
|
-
"actual": normalize_for_compare(actual_value),
|
|
1031
|
-
}
|
|
1032
|
-
)
|
|
1033
|
-
|
|
1034
|
-
return {
|
|
1035
|
-
"ok": not mismatches,
|
|
1036
|
-
"layer": layer,
|
|
1037
|
-
"mismatches": mismatches,
|
|
1038
|
-
"status": "ok" if not mismatches else "drift_detected",
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
def _inject_binding_target(binding_payload: Dict[str, Any], api_record: Mapping[str, Any]) -> Dict[str, Any]:
|
|
1043
|
-
payload = copy.deepcopy(binding_payload)
|
|
1044
|
-
proxy_guid = api_record.get("guid")
|
|
1045
|
-
proxy_id = api_record.get("id")
|
|
1046
|
-
if proxy_guid:
|
|
1047
|
-
for key in ("q_proxy_guid", "proxy_guid", "api_proxy_guid"):
|
|
1048
|
-
payload[key] = proxy_guid
|
|
1049
|
-
if proxy_id not in (None, ""):
|
|
1050
|
-
for key in ("proxy_id", "api_proxy_id"):
|
|
1051
|
-
if key in payload or key == "api_proxy_id":
|
|
1052
|
-
payload[key] = proxy_id
|
|
1053
|
-
payload.setdefault("q_direction", payload.get("direction") or "response")
|
|
1054
|
-
payload.setdefault("direction", payload.get("q_direction") or "response")
|
|
1055
|
-
return payload
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
@dataclass
|
|
1059
|
-
class ApiClient:
|
|
1060
|
-
base_url: str
|
|
1061
|
-
cookie: str = ""
|
|
1062
|
-
language: str = DEFAULT_LANGUAGE
|
|
1063
|
-
user_agent: str = "Codex/api-platform-editor"
|
|
1064
|
-
|
|
1065
|
-
def _request(
|
|
1066
|
-
self,
|
|
1067
|
-
method: str,
|
|
1068
|
-
path: str,
|
|
1069
|
-
*,
|
|
1070
|
-
query: Mapping[str, Any] | None = None,
|
|
1071
|
-
payload: Any = None,
|
|
1072
|
-
headers: Mapping[str, str] | None = None,
|
|
1073
|
-
) -> Any:
|
|
1074
|
-
url = urllib.parse.urljoin(f"{self.base_url}/", path.lstrip("/"))
|
|
1075
|
-
if query:
|
|
1076
|
-
items: list[tuple[str, str]] = []
|
|
1077
|
-
for key, value in query.items():
|
|
1078
|
-
if isinstance(value, list):
|
|
1079
|
-
for item in value:
|
|
1080
|
-
items.append((str(key), str(item)))
|
|
1081
|
-
else:
|
|
1082
|
-
items.append((str(key), str(value)))
|
|
1083
|
-
url = f"{url}?{urllib.parse.urlencode(items, doseq=True)}"
|
|
1084
|
-
request_headers = {
|
|
1085
|
-
"Accept": "application/json, text/plain, */*",
|
|
1086
|
-
"Accept-Language": self.language,
|
|
1087
|
-
"User-Agent": self.user_agent,
|
|
1088
|
-
"X-Requested-With": "XMLHttpRequest",
|
|
1089
|
-
}
|
|
1090
|
-
if self.cookie:
|
|
1091
|
-
request_headers["Cookie"] = self.cookie
|
|
1092
|
-
if headers:
|
|
1093
|
-
request_headers.update({str(key): str(value) for key, value in headers.items()})
|
|
1094
|
-
|
|
1095
|
-
data: bytes | None = None
|
|
1096
|
-
if payload is not None:
|
|
1097
|
-
if isinstance(payload, (bytes, bytearray)):
|
|
1098
|
-
data = bytes(payload)
|
|
1099
|
-
elif isinstance(payload, str):
|
|
1100
|
-
data = payload.encode("utf-8")
|
|
1101
|
-
else:
|
|
1102
|
-
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
1103
|
-
request_headers.setdefault("Content-Type", "application/json")
|
|
1104
|
-
|
|
1105
|
-
request = urllib.request.Request(url, data=data, method=method.upper(), headers=request_headers)
|
|
1106
|
-
context = ssl.create_default_context()
|
|
1107
|
-
context.check_hostname = False
|
|
1108
|
-
context.verify_mode = ssl.CERT_NONE
|
|
1109
|
-
try:
|
|
1110
|
-
with urllib.request.urlopen(request, context=context, timeout=30) as response:
|
|
1111
|
-
body = response.read().decode("utf-8")
|
|
1112
|
-
except urllib.error.HTTPError as exc:
|
|
1113
|
-
detail = exc.read().decode("utf-8", errors="replace")
|
|
1114
|
-
raise SystemExit(f"{method.upper()} {path} failed: {exc.code} {detail}") from exc
|
|
1115
|
-
if not body.strip():
|
|
1116
|
-
return {}
|
|
1117
|
-
try:
|
|
1118
|
-
return json.loads(body)
|
|
1119
|
-
except json.JSONDecodeError:
|
|
1120
|
-
return {"raw": body}
|
|
1121
|
-
|
|
1122
|
-
def call_contract(self, request_contract: Dict[str, Any], submit_payload: Any) -> Any:
|
|
1123
|
-
body = materialize_contract_body(request_contract, submit_payload)
|
|
1124
|
-
return self._request(
|
|
1125
|
-
str(request_contract.get("method") or "POST"),
|
|
1126
|
-
str(request_contract.get("path") or "/"),
|
|
1127
|
-
query=request_contract.get("query") if isinstance(request_contract.get("query"), dict) else None,
|
|
1128
|
-
payload=body,
|
|
1129
|
-
headers=request_contract.get("headers") if isinstance(request_contract.get("headers"), dict) else None,
|
|
1130
|
-
)
|
|
1131
|
-
|
|
1132
|
-
def get_platform_by_key(self, platform_key: str) -> Dict[str, Any]:
|
|
1133
|
-
return self._request("GET", f"/api/api_platform/by_key/{platform_key}")
|
|
1134
|
-
|
|
1135
|
-
def get_instance(self, instance_id: Any) -> Dict[str, Any]:
|
|
1136
|
-
return self._request("GET", f"/api/api_platform_instance/{instance_id}")
|
|
1137
|
-
|
|
1138
|
-
def list_instances(self, platform_guid: str) -> Dict[str, Any]:
|
|
1139
|
-
return self._request("GET", "/api/api_platform_instance", query={"api_platform_guid": platform_guid})
|
|
1140
|
-
|
|
1141
|
-
def get_api(self, api_id: Any) -> Dict[str, Any]:
|
|
1142
|
-
return self._request("GET", f"/api/api_proxy/{api_id}")
|
|
1143
|
-
|
|
1144
|
-
def list_apis(self, platform_guid: str) -> Dict[str, Any]:
|
|
1145
|
-
return self._request("GET", "/api/api_proxy", query={"api_platform_guid": platform_guid})
|
|
1146
|
-
|
|
1147
|
-
def get_binding(self, proxy_guid: str, *, direction: str = "response") -> Dict[str, Any]:
|
|
1148
|
-
return self._request(
|
|
1149
|
-
"GET",
|
|
1150
|
-
"/api/api_proxy_entity_binding",
|
|
1151
|
-
query={"q_proxy_guid": proxy_guid, "q_direction": direction},
|
|
1152
|
-
)
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
def build_client(args: Any) -> ApiClient:
|
|
1156
|
-
return ApiClient(
|
|
1157
|
-
base_url=resolve_editor_base_url(
|
|
1158
|
-
getattr(args, "base_url", None),
|
|
1159
|
-
browser_origin=getattr(args, "browser_origin", None),
|
|
1160
|
-
),
|
|
1161
|
-
cookie=str(getattr(args, "cookie", "") or ""),
|
|
1162
|
-
)
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
def submit_layer(
|
|
1166
|
-
client: ApiClient,
|
|
1167
|
-
*,
|
|
1168
|
-
meta: Dict[str, Any],
|
|
1169
|
-
contract: Dict[str, Any],
|
|
1170
|
-
submit_bundle: Dict[str, Any],
|
|
1171
|
-
) -> Dict[str, Any]:
|
|
1172
|
-
layer = str(meta.get("layer") or submit_bundle.get("layer") or "")
|
|
1173
|
-
requests = contract.get("requests") if isinstance(contract.get("requests"), dict) else {}
|
|
1174
|
-
primary_contract = requests.get("primary")
|
|
1175
|
-
if not isinstance(primary_contract, dict):
|
|
1176
|
-
raise SystemExit("submit blocked: missing primary write contract")
|
|
1177
|
-
|
|
1178
|
-
if layer == "platform":
|
|
1179
|
-
response = client.call_contract(primary_contract, submit_bundle["payload"])
|
|
1180
|
-
platform_key = str(submit_bundle["payload"]["platform_key"])
|
|
1181
|
-
readback = extract_first_record(client.get_platform_by_key(platform_key))
|
|
1182
|
-
verify = summarize_verification(layer="platform", submit_bundle=submit_bundle, readback=readback)
|
|
1183
|
-
return {
|
|
1184
|
-
"response": response,
|
|
1185
|
-
"readback": readback,
|
|
1186
|
-
"verify": verify,
|
|
1187
|
-
"remoteId": readback.get("id"),
|
|
1188
|
-
"remoteGuid": readback.get("guid"),
|
|
1189
|
-
"status": "readback_only" if verify["ok"] else "manual_followup_required",
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
if layer == "instance":
|
|
1193
|
-
response = client.call_contract(primary_contract, submit_bundle["payload"])
|
|
1194
|
-
response_record = extract_first_record(response)
|
|
1195
|
-
remote_id = response_record.get("id") or meta.get("remoteId")
|
|
1196
|
-
readback = extract_first_record(client.get_instance(remote_id))
|
|
1197
|
-
verify = summarize_verification(layer="instance", submit_bundle=submit_bundle, readback=readback)
|
|
1198
|
-
return {
|
|
1199
|
-
"response": response,
|
|
1200
|
-
"readback": readback,
|
|
1201
|
-
"verify": verify,
|
|
1202
|
-
"remoteId": readback.get("id") or remote_id,
|
|
1203
|
-
"remoteGuid": readback.get("guid"),
|
|
1204
|
-
"status": "runtime_pending" if verify["ok"] else "manual_followup_required",
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
if layer != "api":
|
|
1208
|
-
raise SystemExit(f"unsupported submit layer: {layer}")
|
|
1209
|
-
|
|
1210
|
-
response = client.call_contract(primary_contract, submit_bundle["payload"])
|
|
1211
|
-
api_record = extract_first_record(response)
|
|
1212
|
-
remote_id = api_record.get("id") or meta.get("remoteId")
|
|
1213
|
-
if remote_id in (None, ""):
|
|
1214
|
-
raise SystemExit("api submit failed: response did not contain api id")
|
|
1215
|
-
response_binding = submit_bundle.get("response_binding")
|
|
1216
|
-
binding_response: Any = None
|
|
1217
|
-
if response_binding:
|
|
1218
|
-
binding_contract = requests.get("binding")
|
|
1219
|
-
if not isinstance(binding_contract, dict):
|
|
1220
|
-
raise SystemExit("api submit blocked: response_binding exists but binding write contract is missing")
|
|
1221
|
-
binding_payload = _inject_binding_target(response_binding, api_record)
|
|
1222
|
-
binding_response = client.call_contract(binding_contract, binding_payload)
|
|
1223
|
-
response_binding = binding_payload
|
|
1224
|
-
submit_bundle = {**submit_bundle, "response_binding": response_binding}
|
|
1225
|
-
api_readback = extract_first_record(client.get_api(remote_id))
|
|
1226
|
-
proxy_guid = api_readback.get("guid")
|
|
1227
|
-
binding_readback = extract_first_record(client.get_binding(str(proxy_guid))) if proxy_guid else {}
|
|
1228
|
-
readback = {
|
|
1229
|
-
"api": api_readback,
|
|
1230
|
-
"response_binding": binding_readback,
|
|
1231
|
-
}
|
|
1232
|
-
verify = summarize_verification(layer="api", submit_bundle=submit_bundle, readback=readback)
|
|
1233
|
-
return {
|
|
1234
|
-
"response": {
|
|
1235
|
-
"api_proxy": response,
|
|
1236
|
-
"binding": binding_response,
|
|
1237
|
-
},
|
|
1238
|
-
"readback": readback,
|
|
1239
|
-
"verify": verify,
|
|
1240
|
-
"remoteId": api_readback.get("id") or remote_id,
|
|
1241
|
-
"remoteGuid": api_readback.get("guid"),
|
|
1242
|
-
"status": "runtime_pending" if verify["ok"] else "manual_followup_required",
|
|
1243
|
-
"executionOrder": ["api_proxy"] + (["binding"] if response_binding else []) + ["readback"],
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
def build_doc_debug_acceptance(
|
|
1248
|
-
*,
|
|
1249
|
-
work: Dict[str, Any],
|
|
1250
|
-
instance_key: str,
|
|
1251
|
-
api_args: Any,
|
|
1252
|
-
response_summary: str,
|
|
1253
|
-
matched_expected: bool,
|
|
1254
|
-
log_url: str | None = None,
|
|
1255
|
-
) -> Dict[str, Any]:
|
|
1256
|
-
if not str(work.get("doc_url") or "").strip():
|
|
1257
|
-
raise SystemExit("doc-debug acceptance requires doc_url in exported work payload")
|
|
1258
|
-
if not str(instance_key or "").strip():
|
|
1259
|
-
raise SystemExit("doc-debug acceptance requires instance_key")
|
|
1260
|
-
if api_args in (None, ""):
|
|
1261
|
-
raise SystemExit("doc-debug acceptance requires api_args")
|
|
1262
|
-
if not str(response_summary or "").strip():
|
|
1263
|
-
raise SystemExit("doc-debug acceptance requires response summary")
|
|
1264
|
-
return {
|
|
1265
|
-
"layer": "doc-debug",
|
|
1266
|
-
"recordedAt": utc_now_iso(),
|
|
1267
|
-
"docUrl": work["doc_url"],
|
|
1268
|
-
"platformKey": work.get("platform_key"),
|
|
1269
|
-
"apiId": work.get("api_id"),
|
|
1270
|
-
"apiKey": work.get("api_key"),
|
|
1271
|
-
"instanceKey": instance_key,
|
|
1272
|
-
"apiArgs": api_args,
|
|
1273
|
-
"responseSummary": response_summary,
|
|
1274
|
-
"matchedExpected": bool(matched_expected),
|
|
1275
|
-
"logUrl": log_url or "",
|
|
1276
|
-
}
|