promptex-js 0.0.0

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/LICENSE-APACHE ADDED
@@ -0,0 +1,204 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright
52
+ owner or by an individual or Legal Entity authorized to submit on
53
+ behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives,
56
+ including but not limited to communication on electronic mailing
57
+ lists, source code control systems, and issue tracking systems that
58
+ are managed by, or on behalf of, the Licensor for the purpose of
59
+ discussing and improving the Work, but excluding communication that
60
+ is conspicuously marked or otherwise designated in writing by the
61
+ copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing
142
+ the origin of the Work and reproducing the content of the NOTICE
143
+ file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this
154
+ License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright 2026 promptex-ai
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 promptex-ai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # promptex-js(alpha 原型)
2
+
3
+ promptex 的 TypeScript SDK **最小原型**。目前的能力只有一項:宣告 skill,
4
+ 建置成 Claude Code 的 `SKILL.md` 產物。
5
+
6
+ ## 這不是什麼
7
+
8
+ 本套件是早期 alpha,**不是**完整的 promptex。正式版的單一套件內含 SDK、核心的
9
+ 預編譯二進位綁定與完整命令列工具三者;本原型只有 SDK 的最窄一條路徑,命令列
10
+ 工具只有 `build` 一個動詞,沒有原生綁定、沒有多平台投影、沒有引用與關係圖、
11
+ 沒有安裝與所有權登記。plugin 與 adapter 的契約面(`Plugin`、`AdapterContext`、
12
+ `defineTarget` 等)是**介面樁**:型別與簽名逐字複製正式版,方法本體一律拋錯,
13
+ 存在的目的是讓第三方擴充能對本套件編譯並發布;要實際執行,工作區得覆寫成本地的
14
+ 正式版 SDK。
15
+
16
+ 介面與產物格式在正式版之前都會變,不保證任何相容性。正式版發布時本原型會被
17
+ 整份取代。
18
+
19
+ ## 安裝
20
+
21
+ ```bash
22
+ npm install promptex-js@alpha
23
+ ```
24
+
25
+ 需要 Node.js 22.14 以上。
26
+
27
+ ## 用法
28
+
29
+ 把宣告寫在 `prompts/` 下:
30
+
31
+ ```ts
32
+ // prompts/skill.ts
33
+ import { defineSkill } from 'promptex-js'
34
+
35
+ export const commitHelper = defineSkill({
36
+ id: 'commit-helper',
37
+ name: 'Commit 訊息協助',
38
+ config: { whenToUse: '當使用者要求撰寫 commit 訊息時使用' },
39
+ content: [
40
+ '依 Conventional Commits 撰寫:type(scope): subject。',
41
+ 'subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。',
42
+ ],
43
+ })
44
+ ```
45
+
46
+ 建置:
47
+
48
+ ```bash
49
+ npx promptex build
50
+ ```
51
+
52
+ 產出 `./.claude/skills/commit-helper/SKILL.md`:
53
+
54
+ ```text
55
+ ---
56
+ name: commit-helper
57
+ description: 當使用者要求撰寫 commit 訊息時使用
58
+ ---
59
+
60
+ 依 Conventional Commits 撰寫:type(scope): subject。
61
+
62
+ subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。
63
+ ```
64
+
65
+ `.ts` 宣告檔不需要先經過建置步驟,命令列工具靠 Node 的型別剝離直接載入。
66
+
67
+ ### 命令列選項
68
+
69
+ ```text
70
+ promptex build [--src <目錄>] [--out <目錄>]
71
+
72
+ --src <目錄> 宣告檔所在目錄,預設 prompts
73
+ --out <目錄> 產物輸出目錄,預設當前目錄
74
+ ```
75
+
76
+ ### 程式化呼叫
77
+
78
+ ```ts
79
+ import { build, defineSkill, renderSkill } from 'promptex-js'
80
+
81
+ defineSkill({ /* ... */ })
82
+ const written = await build('.')
83
+ ```
84
+
85
+ ## 授權
86
+
87
+ MIT OR Apache-2.0,見 `LICENSE-MIT` 與 `LICENSE-APACHE`。
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ // promptex 命令列工具(alpha 原型)。
3
+ //
4
+ // 只有一個動詞:`build`。載入來源目錄下的宣告檔,把登記處內的 skill 投影
5
+ // 成 SKILL.md。正式版的其餘動詞(evaluate、declare、config、diagnostics)
6
+ // 不在本原型範圍內。
7
+
8
+ import { spawnSync } from 'node:child_process'
9
+ import { readdir, stat } from 'node:fs/promises'
10
+ import { join, resolve } from 'node:path'
11
+ import { pathToFileURL } from 'node:url'
12
+
13
+ const USAGE = `promptex(alpha 原型)
14
+
15
+ 用法:
16
+ promptex build [--src <目錄>] [--out <目錄>]
17
+
18
+ 選項:
19
+ --src <目錄> 宣告檔所在目錄,預設 prompts
20
+ --out <目錄> 產物輸出目錄,預設當前目錄
21
+ --help 顯示本說明
22
+ `
23
+
24
+ /** 宣告檔的副檔名。`.ts` 依賴 Node 的型別剝離,不經過額外的建置步驟。 */
25
+ const SOURCE_EXTENSIONS = ['.ts', '.mts', '.js', '.mjs']
26
+
27
+ function parseArgs(argv) {
28
+ const args = { verb: argv[0], src: 'prompts', out: '.' }
29
+ for (let i = 1; i < argv.length; i += 1) {
30
+ const flag = argv[i]
31
+ if (flag === '--src' || flag === '--out') {
32
+ const value = argv[i + 1]
33
+ if (value === undefined) throw new Error(`${flag} 後面缺少值`)
34
+ args[flag.slice(2)] = value
35
+ i += 1
36
+ } else {
37
+ throw new Error(`未知的選項:${flag}`)
38
+ }
39
+ }
40
+ return args
41
+ }
42
+
43
+ /** 遞迴列出來源目錄下的宣告檔,依路徑排序讓載入順序不隨檔案系統而變。 */
44
+ async function collectSources(dir) {
45
+ const entries = await readdir(dir, { withFileTypes: true })
46
+ const found = []
47
+ for (const entry of entries) {
48
+ const path = join(dir, entry.name)
49
+ if (entry.isDirectory()) found.push(...(await collectSources(path)))
50
+ else if (SOURCE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) found.push(path)
51
+ }
52
+ return found.sort()
53
+ }
54
+
55
+ async function main() {
56
+ const argv = process.argv.slice(2)
57
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
58
+ process.stdout.write(USAGE)
59
+ return
60
+ }
61
+
62
+ const args = parseArgs(argv)
63
+ if (args.verb !== 'build') {
64
+ process.stderr.write(`未知的動詞:${args.verb}\n\n${USAGE}`)
65
+ process.exitCode = 1
66
+ return
67
+ }
68
+
69
+ const srcDir = resolve(args.src)
70
+ try {
71
+ if (!(await stat(srcDir)).isDirectory()) throw new Error('不是目錄')
72
+ } catch {
73
+ process.stderr.write(`找不到來源目錄:${srcDir}\n`)
74
+ process.exitCode = 1
75
+ return
76
+ }
77
+
78
+ const sources = await collectSources(srcDir)
79
+ if (sources.length === 0) {
80
+ process.stderr.write(`來源目錄沒有宣告檔(${SOURCE_EXTENSIONS.join('、')}):${srcDir}\n`)
81
+ process.exitCode = 1
82
+ return
83
+ }
84
+
85
+ // 載入宣告檔與呼叫 build 必須共用同一個模組實例,登記處才看得到宣告;
86
+ // 兩邊都經 `promptex-js` 的 dist 進入點解析,因此指向同一個模組。
87
+ const { build, declaredCount } = await import('../dist/index.js')
88
+ for (const source of sources) await import(pathToFileURL(source).href)
89
+
90
+ if (declaredCount() === 0) {
91
+ process.stderr.write(`載入了 ${sources.length} 份宣告檔,但沒有任何 skill 被宣告。\n`)
92
+ process.exitCode = 1
93
+ return
94
+ }
95
+
96
+ for (const path of await build(resolve(args.out))) process.stdout.write(`${path}\n`)
97
+ }
98
+
99
+ // Node 未內建型別剝離時(22.18 之前)以旗標重跑一次,讓 `.ts` 宣告檔不必
100
+ // 先經過建置步驟。已內建的版本不重跑,避免多開一個行程。
101
+ if (!process.features.typescript) {
102
+ const result = spawnSync(
103
+ process.execPath,
104
+ ['--experimental-strip-types', new URL(import.meta.url).pathname, ...process.argv.slice(2)],
105
+ { stdio: 'inherit' },
106
+ )
107
+ process.exit(result.status ?? 1)
108
+ } else {
109
+ await main().catch((error) => {
110
+ process.stderr.write(`${error.message}\n`)
111
+ process.exitCode = 1
112
+ })
113
+ }
@@ -0,0 +1,59 @@
1
+ import type { Kind } from './ir.js';
2
+ import type { PluginEntry } from './plugin.js';
3
+ import type { SelectSpec } from './registry.js';
4
+ /** 降級或不支援的一筆記錄,與核心 `adapter::DegradeEntry` 同型。 */
5
+ export interface DegradeItem {
6
+ readonly kind: Kind;
7
+ readonly nodeId: string;
8
+ readonly feature: string;
9
+ /** 降級前後的強制力層級;純機制缺失(不支援)而無強制力落差時省略。 */
10
+ readonly from?: Enforcement;
11
+ readonly to?: Enforcement;
12
+ readonly note: string;
13
+ }
14
+ /** 強制力階梯:機械閘 > 流程閘 > 措辭層,列舉封閉。 */
15
+ export type Enforcement = 'mechanical' | 'processGate' | 'wording';
16
+ /** 一次第三方投影的安裝報告,與內建平台的 `Report` 同一形態。 */
17
+ export interface EmitReport {
18
+ readonly platform: string;
19
+ readonly emitted: readonly string[];
20
+ readonly degraded: readonly DegradeItem[];
21
+ readonly unsupported: readonly DegradeItem[];
22
+ }
23
+ /** 第三方 adapter 的公開介面:官方與第三方適配使用同一組方法。 */
24
+ export interface AdapterContext {
25
+ /** 本平台要產出的節點(省略 kind 即全部)。 */
26
+ entries(kind?: Kind): readonly PluginEntry[];
27
+ /** 依落點表渲染節點內容:第三個參數是落點對照表,不是回呼函式。 */
28
+ render(entry: PluginEntry, selfPath: string, layout: ReadonlyMap<string, string>): string;
29
+ /** 本節點為本平台宣告的平台原生鍵覆寫;未宣告或空物件時回傳 `undefined`。 */
30
+ overrides(entry: PluginEntry): Readonly<Record<string, unknown>> | undefined;
31
+ /** 本節點宣告的框架保留鍵(`promptex:` 命名空間);未宣告時回傳 `undefined`。 */
32
+ reserved(entry: PluginEntry): Readonly<Record<string, string>> | undefined;
33
+ /** 本節點在本平台的產物沒有承載鍵的位置時,把該筆記進不支援清單。 */
34
+ unsupportedOverride(entry: PluginEntry, form: string): void;
35
+ /** 記錄能力降級,進安裝報告。 */
36
+ degrade(item: DegradeItem): void;
37
+ /** 記錄平台不支援而未產出的節點,進安裝報告。 */
38
+ unsupported(item: DegradeItem): void;
39
+ /** 把本次累積的降級與不支援併成安裝報告。 */
40
+ report(platform: string, emitted: readonly string[]): EmitReport;
41
+ /** 是否累積了任何降級或不支援記錄。 */
42
+ hasNotes(): boolean;
43
+ }
44
+ export type AdapterEmit = (ctx: AdapterContext) => Map<string, string>;
45
+ /** 第三方適配的 target:與內建 `claude()`/`codex()` 同形,多帶一個 `emit`。 */
46
+ export interface AdapterTarget {
47
+ readonly platform: string;
48
+ readonly emit: AdapterEmit;
49
+ /** 本適配接受哪些建構參數,標準 JSON Schema。 */
50
+ readonly configSchema?: unknown;
51
+ }
52
+ /** 第三方套件用本函式建構 target。 */
53
+ export declare function defineTarget(platform: string, emit: AdapterEmit, options?: {
54
+ readonly configSchema?: unknown;
55
+ }): AdapterTarget;
56
+ /** 格式化為人讀文字:正式版委派核心 `adapter::Report::format`。 */
57
+ export declare function formatReport(report: EmitReport): string;
58
+ /** 建立一份 `AdapterContext` 供命令列呼叫第三方 `emit` 或 `extend` 函式。 */
59
+ export declare function createAdapterContext(platform: string, select?: SelectSpec): AdapterContext;
@@ -0,0 +1,38 @@
1
+ // 第三方 adapter 的公開介面(介面樁):型別逐字複製正式版
2
+ // packages/promptex-js/src/adapter.ts。
3
+ //
4
+ // 照抄與樁的分界:`defineTarget` 只是組一個物件,照抄;`createAdapterContext`
5
+ // 回傳物件的 `degrade`/`unsupported`/`report`/`hasNotes` 只碰自身閉包,照抄;
6
+ // `entries`/`render`/`overrides`/`reserved`/`unsupportedOverride` 要查註冊表
7
+ // 或委派核心,本體為樁;`formatReport` 委派核心的報告渲染,本體為樁。
8
+ import { stub } from './stub.js';
9
+ /** 第三方套件用本函式建構 target。 */
10
+ export function defineTarget(platform, emit, options = {}) {
11
+ return {
12
+ platform,
13
+ emit,
14
+ ...(options.configSchema !== undefined ? { configSchema: options.configSchema } : {}),
15
+ };
16
+ }
17
+ /** 格式化為人讀文字:正式版委派核心 `adapter::Report::format`。 */
18
+ export function formatReport(report) {
19
+ void report;
20
+ return stub('formatReport');
21
+ }
22
+ /** 建立一份 `AdapterContext` 供命令列呼叫第三方 `emit` 或 `extend` 函式。 */
23
+ export function createAdapterContext(platform, select) {
24
+ void select;
25
+ const degraded = [];
26
+ const unsupported = [];
27
+ return {
28
+ entries: () => stub('AdapterContext.entries'),
29
+ render: () => stub('AdapterContext.render'),
30
+ overrides: () => stub('AdapterContext.overrides'),
31
+ reserved: () => stub('AdapterContext.reserved'),
32
+ unsupportedOverride: () => stub('AdapterContext.unsupportedOverride'),
33
+ degrade: (item) => degraded.push(item),
34
+ unsupported: (item) => unsupported.push(item),
35
+ report: (platform, emitted) => ({ platform, emitted: [...emitted], degraded: [...degraded], unsupported: [...unsupported] }),
36
+ hasNotes: () => degraded.length > 0 || unsupported.length > 0,
37
+ };
38
+ }
@@ -0,0 +1,5 @@
1
+ import type { Piece } from './ir.js';
2
+ /** 建構函式的回傳值。包一層是為了與純字串區分,避免內容陣列的元素型別歧義。 */
3
+ export interface MDNode {
4
+ readonly __piece: Piece;
5
+ }
@@ -0,0 +1,4 @@
1
+ // 內容建構函式的回傳型別(介面樁):只承載正式版 packages/promptex-js/src/content.ts
2
+ // 對外匯出的 `MDNode`,逐字複製。建構函式本體(`prose`/`section` 等)不在
3
+ // 本樁範圍。
4
+ export {};
package/dist/diag.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** 嚴重度:阻斷級中止建置,非阻斷級列入報告後放行。 */
2
+ export type Severity = 'error' | 'warning';
3
+ /** 一筆診斷。代碼、訊息、位置三項必含;`at` 是陣列以便同時指出兩處宣告的位置。 */
4
+ export interface Diagnostic {
5
+ code: string;
6
+ message: string;
7
+ at: string[];
8
+ hint?: string;
9
+ severity?: Severity;
10
+ }
11
+ /** 本批診斷是否含阻斷級項目。 */
12
+ export declare function hasErrors(diags: readonly Diagnostic[]): boolean;
13
+ /**
14
+ * 一筆診斷的人讀形態,逐行回傳:嚴重度標記(阻斷級 `✗`、非阻斷級 `※`)、
15
+ * 位置逐一列出、有提示才列提示。
16
+ */
17
+ export declare function formatDiagnostic(d: Diagnostic): string[];
package/dist/diag.js ADDED
@@ -0,0 +1,20 @@
1
+ // 診斷的型別與人讀格式(介面樁):逐字複製正式版 packages/promptex-js/src/diag.ts
2
+ // 的公開型別與兩個純函式。診斷本身不含引擎邏輯,因此照抄而非樁;位置捕捉
3
+ // (`captureAt`)與相似度計算屬求值期內部工具,不在公開匯出面,不帶。
4
+ /** 本批診斷是否含阻斷級項目。 */
5
+ export function hasErrors(diags) {
6
+ return diags.some((d) => (d.severity ?? 'error') === 'error');
7
+ }
8
+ /**
9
+ * 一筆診斷的人讀形態,逐行回傳:嚴重度標記(阻斷級 `✗`、非阻斷級 `※`)、
10
+ * 位置逐一列出、有提示才列提示。
11
+ */
12
+ export function formatDiagnostic(d) {
13
+ const marker = (d.severity ?? 'error') === 'error' ? '✗' : '※';
14
+ const lines = [`${marker} ${d.code} ${d.message}`];
15
+ for (const at of d.at)
16
+ lines.push(` at ${at}`);
17
+ if (d.hint)
18
+ lines.push(` ${d.hint}`);
19
+ return lines;
20
+ }
@@ -0,0 +1,50 @@
1
+ import type { Ref } from './registry.js';
2
+ export type { Content, ContentPiece, Ref, SelectSpec } from './registry.js';
3
+ export type { Ir, Kind, Node, Piece, Provenance, RefTarget } from './ir.js';
4
+ export type { MDNode } from './content.js';
5
+ export type { LockEntry, Plugin, PluginEntry, PrepareContext, TransformContext, ValidateContext } from './plugin.js';
6
+ export { createAdapterContext, defineTarget, formatReport, type AdapterContext, type AdapterEmit, type AdapterTarget, type DegradeItem, type EmitReport, type Enforcement, } from './adapter.js';
7
+ export { formatDiagnostic, hasErrors, type Diagnostic, type Severity } from './diag.js';
8
+ /** skill 的觸發設定。 */
9
+ export interface SkillConfig {
10
+ /** 觸發語料,投影為產物 frontmatter 的 `description`。 */
11
+ whenToUse: string;
12
+ }
13
+ /** 一份 skill 的宣告。本原型只承載正式版 `SkillDef` 的最小子集。 */
14
+ export interface SkillDef {
15
+ /** 資源識別,同時是產物目錄名。 */
16
+ id: string;
17
+ /** 顯示名稱。 */
18
+ name: string;
19
+ /** 觸發設定。 */
20
+ config: SkillConfig;
21
+ /** 內容。單段用字串,多段用陣列,段落之間以空行分隔。 */
22
+ content: string | string[];
23
+ }
24
+ /**
25
+ * 宣告一份 skill。
26
+ *
27
+ * 宣告本身不寫檔;產物在 {@link build} 被呼叫時一次產出。
28
+ */
29
+ export declare function defineSkill(def: SkillDef): Ref<'skill'>;
30
+ /** 目前已登記的宣告數。供呼叫端在建置前自我核對用。 */
31
+ export declare const declaredCount: () => number;
32
+ /**
33
+ * 把一份 skill 投影成 SKILL.md 的完整內容。
34
+ *
35
+ * frontmatter 的 `name` 取 id 而非顯示名稱:平台側以 `name` 作為喚起時的識別。
36
+ */
37
+ export declare function renderSkill(skill: {
38
+ id: string;
39
+ whenToUse: string;
40
+ content: string[];
41
+ }): string;
42
+ /** 一份 skill 在輸出目錄下的產物路徑。 */
43
+ export declare const skillPath: (outDir: string, id: string) => string;
44
+ /**
45
+ * 把目前登記的全部宣告投影到輸出目錄,回傳產物路徑。
46
+ *
47
+ * 呼叫後登記處清空:同一行程內連續建置兩個輸出目錄時,第二次不該重複寫出
48
+ * 第一次的內容。
49
+ */
50
+ export declare function build(outDir: string): Promise<string[]>;
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ // promptex-js(alpha 原型):TypeScript SDK 的公開入口。
2
+ //
3
+ // 目前的能力只有一條路徑:宣告 skill,投影成 Claude Code 的 SKILL.md。
4
+ // 正式版的核心綁定、多平台投影、引用與關係圖都不在本原型範圍內。
5
+ import { mkdir, writeFile } from 'node:fs/promises';
6
+ import { dirname, join } from 'node:path';
7
+ export { createAdapterContext, defineTarget, formatReport, } from './adapter.js';
8
+ export { formatDiagnostic, hasErrors } from './diag.js';
9
+ // 模組層級的登記處:宣告散落在多個檔案時,逐一回傳並手動彙整會讓每個檔案
10
+ // 都得認識彙整點。正式版的收集語意相同。
11
+ const registry = [];
12
+ /**
13
+ * id 是否可安全作為單層目錄名。
14
+ *
15
+ * 產物路徑由 id 直接組成,不擋下來的話 `../` 這類值會把檔案寫到輸出目錄之外。
16
+ */
17
+ const isValidId = (id) => id.length > 0 && !id.includes('/') && !id.includes('\\') && id !== '.' && id !== '..';
18
+ /**
19
+ * 宣告一份 skill。
20
+ *
21
+ * 宣告本身不寫檔;產物在 {@link build} 被呼叫時一次產出。
22
+ */
23
+ export function defineSkill(def) {
24
+ if (!isValidId(def.id)) {
25
+ throw new Error(`skill id 不可為空、且不可含 \`/\`、\`\\\` 或 \`..\`:${JSON.stringify(def.id)}`);
26
+ }
27
+ registry.push({
28
+ id: def.id,
29
+ name: def.name,
30
+ whenToUse: def.config.whenToUse,
31
+ content: Array.isArray(def.content) ? def.content : [def.content],
32
+ });
33
+ return { kind: 'skill', id: def.id };
34
+ }
35
+ /** 目前已登記的宣告數。供呼叫端在建置前自我核對用。 */
36
+ export const declaredCount = () => registry.length;
37
+ /**
38
+ * 把一份 skill 投影成 SKILL.md 的完整內容。
39
+ *
40
+ * frontmatter 的 `name` 取 id 而非顯示名稱:平台側以 `name` 作為喚起時的識別。
41
+ */
42
+ export function renderSkill(skill) {
43
+ const header = `---\nname: ${skill.id}\ndescription: ${skill.whenToUse}\n---\n`;
44
+ return skill.content.length === 0 ? header : `${header}\n${skill.content.join('\n\n')}\n`;
45
+ }
46
+ /** 一份 skill 在輸出目錄下的產物路徑。 */
47
+ export const skillPath = (outDir, id) => join(outDir, '.claude', 'skills', id, 'SKILL.md');
48
+ /**
49
+ * 把目前登記的全部宣告投影到輸出目錄,回傳產物路徑。
50
+ *
51
+ * 呼叫後登記處清空:同一行程內連續建置兩個輸出目錄時,第二次不該重複寫出
52
+ * 第一次的內容。
53
+ */
54
+ export async function build(outDir) {
55
+ const skills = registry.splice(0, registry.length);
56
+ const written = [];
57
+ for (const skill of skills) {
58
+ const path = skillPath(outDir, skill.id);
59
+ await mkdir(dirname(path), { recursive: true });
60
+ await writeFile(path, renderSkill(skill), 'utf8');
61
+ written.push(path);
62
+ }
63
+ return written;
64
+ }
package/dist/ir.d.ts ADDED
@@ -0,0 +1,90 @@
1
+ /** 資源類型:集合封閉,不可由擴充新增。 */
2
+ export type Kind = 'skill' | 'rule' | 'agent' | 'hook' | 'mcp' | 'instruction' | 'permission' | 'resource' | 'asset' | 'dir';
3
+ /** 引用目標:類型加識別字的複合鍵。 */
4
+ export interface RefTarget {
5
+ kind: Kind;
6
+ id: string;
7
+ }
8
+ /** 內容片段:以資料結構表達,不含任何平台的渲染結果。欄位順序即契約。 */
9
+ export type Piece = {
10
+ t: 'prose';
11
+ md: string;
12
+ } | {
13
+ t: 'section';
14
+ title: string;
15
+ children: Piece[];
16
+ } | {
17
+ t: 'table';
18
+ header: string[];
19
+ rows: string[][];
20
+ } | {
21
+ t: 'list';
22
+ items: string[];
23
+ } | {
24
+ t: 'check';
25
+ items: string[];
26
+ } | {
27
+ t: 'link';
28
+ name: string;
29
+ url: string;
30
+ } | {
31
+ t: 'code';
32
+ lang: string;
33
+ code: string;
34
+ } | {
35
+ t: 'quote';
36
+ children: Piece[];
37
+ } | {
38
+ t: 'divider';
39
+ } | {
40
+ t: 'ordered';
41
+ items: string[];
42
+ } | {
43
+ t: 'details';
44
+ summary: string;
45
+ children: Piece[];
46
+ } | {
47
+ t: 'image';
48
+ alt: string;
49
+ src: string;
50
+ } | {
51
+ t: 'file';
52
+ path: string;
53
+ } | {
54
+ t: 'ref';
55
+ target: RefTarget;
56
+ } | {
57
+ t: 'bold';
58
+ children: Piece[];
59
+ } | {
60
+ t: 'italic';
61
+ children: Piece[];
62
+ } | {
63
+ t: 'inlineCode';
64
+ text: string;
65
+ } | {
66
+ t: 'inlineLink';
67
+ name: string;
68
+ url: string;
69
+ };
70
+ export interface Node {
71
+ id: string;
72
+ name: string;
73
+ kind: Kind;
74
+ config?: Record<string, unknown>;
75
+ meta?: Record<string, unknown>;
76
+ content: Piece[];
77
+ }
78
+ export interface Provenance {
79
+ sourceCommit: string;
80
+ confHash: string;
81
+ engineVersion: string;
82
+ }
83
+ export interface Ir {
84
+ version: string;
85
+ provenance: Provenance;
86
+ nodes: Node[];
87
+ resources: Node[];
88
+ /** 節點識別(`分類:識別`)對來源位置(`相對專案根的路徑:行號`)。 */
89
+ sources: Record<string, string>;
90
+ }
package/dist/ir.js ADDED
@@ -0,0 +1,3 @@
1
+ // 中介表示的型別(介面樁):逐字複製正式版 packages/promptex-js/src/ir.ts 的
2
+ // 公開型別。純型別,執行期不存在。
3
+ export {};
@@ -0,0 +1,68 @@
1
+ import type { Diagnostic } from './diag.js';
2
+ import type { Kind } from './ir.js';
3
+ import type { ContentPiece } from './registry.js';
4
+ /** plugin 生命週期看到的節點視圖;`def` 與登記表內部共用同一份物件參照。 */
5
+ export interface PluginEntry<K extends Kind = Kind> {
6
+ readonly id: string;
7
+ readonly kind: K;
8
+ readonly name: string;
9
+ /** 宣告在源碼中的位置,供診斷指出節點定義於何處。 */
10
+ readonly at: string;
11
+ readonly def: {
12
+ id: string;
13
+ name: string;
14
+ kind: Kind;
15
+ description?: string;
16
+ config?: Record<string, unknown>;
17
+ meta?: Record<string, unknown>;
18
+ content: unknown;
19
+ };
20
+ }
21
+ export interface ValidateContext {
22
+ /** 當下註冊表的全部節點(不含外部引用佔位),依 id 排序。 */
23
+ readonly entries: readonly PluginEntry[];
24
+ /** 限定某個 kind 的節點清單。 */
25
+ entriesOf(kind: Kind): readonly PluginEntry[];
26
+ /** 本輪求值的專案根,與 `PrepareContext.projectRoot` 同一個值。 */
27
+ readonly projectRoot: string;
28
+ /** 讀本 plugin 的自訂參數(`meta.plugins[pluginName]`);未宣告回傳 undefined。 */
29
+ params(entry: PluginEntry): unknown;
30
+ }
31
+ export interface TransformContext extends ValidateContext {
32
+ /** 對節點的 content 追加一段內容(疊加型改寫)。 */
33
+ appendContent(entry: PluginEntry, content: ContentPiece): void;
34
+ /** 合併進節點的 config(覆寫型改寫);衝突偵測到鍵的層級。 */
35
+ patchConfig(entry: PluginEntry, patch: Record<string, unknown>): void;
36
+ }
37
+ /** 外部依賴的一筆鎖定記錄。 */
38
+ export interface LockEntry {
39
+ readonly id: string;
40
+ readonly source: string;
41
+ readonly version: string;
42
+ }
43
+ /** 準備階段看到的框架協助:快取落點與鎖定檔由框架統一提供。 */
44
+ export interface PrepareContext {
45
+ /** `{專案根}/.promptex/cache/{pluginName}/`,呼叫 `prepare` 前已確保存在。 */
46
+ readonly cacheDir: string;
47
+ /** 本輪求值的專案根。 */
48
+ readonly projectRoot: string;
49
+ /** 寫入本 plugin 的鎖定區段。 */
50
+ writeLock(entries: readonly LockEntry[]): void;
51
+ }
52
+ export interface Plugin {
53
+ readonly name: string;
54
+ /** 這個擴充作用在哪幾種節點類型;未宣告即不限。 */
55
+ readonly kinds?: readonly Kind[];
56
+ /** 本擴充接受哪些建構參數,標準 JSON Schema;純資料,穿得過中介表示的邊界。 */
57
+ readonly configSchema?: unknown;
58
+ /** 各語系的覆蓋層:語系標籤 → 「JSON Pointer → 替換值」的對照。 */
59
+ readonly configSchemaLocales?: Record<string, unknown>;
60
+ /** 本擴充相容的框架版本範圍,caret 前綴形態(如 `'^2.0.0'`);省略即不限。 */
61
+ readonly version?: string;
62
+ /** 唯一允許 async 的生命週期,於收集遍之前執行。 */
63
+ prepare?(ctx: PrepareContext): Promise<void>;
64
+ /** 解析遍:對註冊表做結構驗證,回傳診斷(空陣列即通過)。 */
65
+ validate?(ctx: ValidateContext): Diagnostic[];
66
+ /** 改寫遍:改寫既有節點、以 define* 新增節點。 */
67
+ transform?(ctx: TransformContext): void;
68
+ }
package/dist/plugin.js ADDED
@@ -0,0 +1,6 @@
1
+ // plugin 生命週期的型別契約(介面樁):逐字複製正式版
2
+ // packages/promptex-js/src/plugin.ts 的公開型別。全是 interface,執行期不存在。
3
+ //
4
+ // 生命週期固定順序:prepare(唯一 async,收集遍之前)→ 源碼求值 → transform
5
+ // (改寫遍)→ resolve(解析遍:核心檢查在先,plugin validate 隨後)。
6
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { MDNode } from './content.js';
2
+ import type { Kind } from './ir.js';
3
+ /** 內容欄位可接受的形態:純文字、建構函式結果、引用,或它們的陣列。 */
4
+ export type ContentPiece = string | MDNode | Ref;
5
+ export type Content = ContentPiece | readonly ContentPiece[];
6
+ /**
7
+ * 宣告函式的回傳值:帶來源資源的類型資訊。同時是引用函式的回傳值,可直接
8
+ * 放進另一個節點的 content。`kind` 是編譯期可見的字面量類型。
9
+ */
10
+ export interface Ref<K extends Kind = Kind> {
11
+ readonly id: string;
12
+ readonly kind: K;
13
+ }
14
+ /** 配置單元的分發映射:`tags` 前綴匹配、多個為 OR;`exclude` 優先於 `tags`。 */
15
+ export interface SelectSpec {
16
+ readonly tags?: readonly string[];
17
+ readonly exclude?: readonly string[];
18
+ }
@@ -0,0 +1,4 @@
1
+ // 註冊表相關的公開型別(介面樁):只承載正式版 packages/promptex-js/src/registry.ts
2
+ // 對外匯出的四個型別,逐字複製。註冊表本體(`register`/`engine`/求值)不在
3
+ // 本樁範圍。
4
+ export {};
package/dist/stub.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare class PromptexStubError extends Error {
2
+ readonly name = "PromptexStubError";
3
+ constructor(what: string);
4
+ }
5
+ export declare const stub: (what: string) => never;
package/dist/stub.js ADDED
@@ -0,0 +1,16 @@
1
+ // 介面樁的統一落點:訊息帶套件名與版號,讓「裝到的是樁」在第一個錯誤就看得
2
+ // 出來,而不是在某個 undefined 或空陣列上安靜地繼續。
3
+ //
4
+ // 不從套件根匯出:`PromptexStubError` 不是正式版的公開面,匯出它會讓樁的 .d.ts
5
+ // 多出一個正式版沒有的名字。
6
+ const PACKAGE = 'promptex-js 0.0.0';
7
+ export class PromptexStubError extends Error {
8
+ name = 'PromptexStubError';
9
+ constructor(what) {
10
+ super(`promptex 介面樁(${PACKAGE}):\`${what}\` 沒有實作。` +
11
+ '本版只提供型別與函式簽名讓擴充能編譯;要實際執行,請把工作區的 pnpm overrides(link:)指向本地 promptex 框架,或等正式版發布。');
12
+ }
13
+ }
14
+ export const stub = (what) => {
15
+ throw new PromptexStubError(what);
16
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "promptex-js",
3
+ "version": "0.0.0",
4
+ "description": "promptex 的 TypeScript SDK 最小原型(alpha):宣告 skill 並投影成 SKILL.md,並提供 plugin 與 adapter 契約的介面樁(只有型別與簽名,沒有實作)",
5
+ "license": "MIT OR Apache-2.0",
6
+ "author": "promptex-ai",
7
+ "homepage": "https://github.com/promptex-ai/promptex#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/promptex-ai/promptex.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/promptex-ai/promptex/issues"
14
+ },
15
+ "keywords": [
16
+ "prompt",
17
+ "prompt-engineering",
18
+ "ai",
19
+ "llm",
20
+ "agent",
21
+ "claude",
22
+ "skills",
23
+ "codegen"
24
+ ],
25
+ "type": "module",
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "bin": {
35
+ "promptex": "./bin/promptex.mjs"
36
+ },
37
+ "engines": {
38
+ "node": ">=22.14.0"
39
+ },
40
+ "files": [
41
+ "dist",
42
+ "bin",
43
+ "README.md",
44
+ "LICENSE-MIT",
45
+ "LICENSE-APACHE"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.json",
49
+ "prepack": "npm run build",
50
+ "test": "node --test 'test/*.test.mjs'"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^22.10.0",
54
+ "typescript": "^5.7.0"
55
+ }
56
+ }