@lingfan-engine/stories-build 0.0.0-stage → 0.1.2

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.
Files changed (110) hide show
  1. package/LICENSE +201 -0
  2. package/bin/stories-build.mjs +16 -0
  3. package/bin/stories-watch.mjs +16 -0
  4. package/package.json +50 -3
  5. package/src/authoring.d.ts +51 -0
  6. package/src/cell/errors.ts +12 -0
  7. package/src/cell/imports.ts +127 -0
  8. package/src/cell/index.ts +33 -0
  9. package/src/cell/render-register.ts +33 -0
  10. package/src/cell/scan-cells.ts +63 -0
  11. package/src/cell/scan-file.ts +108 -0
  12. package/src/cell/types.ts +27 -0
  13. package/src/cell/whitelist.ts +22 -0
  14. package/src/cli/cli.ts +99 -0
  15. package/src/cli/watch-cli.ts +42 -0
  16. package/src/compiler/cell-scan.ts +27 -0
  17. package/src/compiler/compiler-contract.ts +87 -0
  18. package/src/compiler/extension-load.ts +67 -0
  19. package/src/compiler/index.ts +22 -0
  20. package/src/compiler/story-compiler/assemble/functions.ts +202 -0
  21. package/src/compiler/story-compiler/assemble/index.ts +8 -0
  22. package/src/compiler/story-compiler/assemble/session.ts +207 -0
  23. package/src/compiler/story-compiler/assemble/types.ts +37 -0
  24. package/src/compiler/story-compiler/assemble.ts +5 -0
  25. package/src/compiler/story-compiler/graph/build.ts +208 -0
  26. package/src/compiler/story-compiler/graph/core.ts +102 -0
  27. package/src/compiler/story-compiler/graph/fold.ts +121 -0
  28. package/src/compiler/story-compiler/graph/index.ts +17 -0
  29. package/src/compiler/story-compiler/graph/scan/bindings.ts +277 -0
  30. package/src/compiler/story-compiler/graph/scan/imports.ts +170 -0
  31. package/src/compiler/story-compiler/graph/scan/index.ts +9 -0
  32. package/src/compiler/story-compiler/graph/scan/module-scan.ts +199 -0
  33. package/src/compiler/story-compiler/graph/state-root.ts +147 -0
  34. package/src/compiler/story-compiler/graph.ts +18 -0
  35. package/src/compiler/story-compiler/index.ts +34 -0
  36. package/src/compiler/story-compiler/translate/expr/assign.ts +204 -0
  37. package/src/compiler/story-compiler/translate/expr/engine-text.ts +16 -0
  38. package/src/compiler/story-compiler/translate/expr/expr.ts +174 -0
  39. package/src/compiler/story-compiler/translate/expr/index.ts +24 -0
  40. package/src/compiler/story-compiler/translate/expr/lower/index.ts +4 -0
  41. package/src/compiler/story-compiler/translate/expr/lower/lower.ts +266 -0
  42. package/src/compiler/story-compiler/translate/expr/lower/numeric.ts +56 -0
  43. package/src/compiler/story-compiler/translate/expr/probe.ts +23 -0
  44. package/src/compiler/story-compiler/translate/expr/state-path.ts +47 -0
  45. package/src/compiler/story-compiler/translate/expr/words/arg.ts +87 -0
  46. package/src/compiler/story-compiler/translate/expr/words/call.ts +125 -0
  47. package/src/compiler/story-compiler/translate/expr/words/callee.ts +43 -0
  48. package/src/compiler/story-compiler/translate/expr/words/command.ts +93 -0
  49. package/src/compiler/story-compiler/translate/expr/words/dispatch.ts +16 -0
  50. package/src/compiler/story-compiler/translate/expr/words/index.ts +8 -0
  51. package/src/compiler/story-compiler/translate/expr/words/static-for.ts +96 -0
  52. package/src/compiler/story-compiler/translate/font-check.ts +94 -0
  53. package/src/compiler/story-compiler/translate/index.ts +10 -0
  54. package/src/compiler/story-compiler/translate/shared.ts +132 -0
  55. package/src/compiler/story-compiler/translate/stmt/control/branch.ts +71 -0
  56. package/src/compiler/story-compiler/translate/stmt/control/index.ts +11 -0
  57. package/src/compiler/story-compiler/translate/stmt/control/iter.ts +72 -0
  58. package/src/compiler/story-compiler/translate/stmt/control/loop.ts +114 -0
  59. package/src/compiler/story-compiler/translate/stmt/control/switch.ts +75 -0
  60. package/src/compiler/story-compiler/translate/stmt/control-flow.ts +25 -0
  61. package/src/compiler/story-compiler/translate/stmt/index.ts +17 -0
  62. package/src/compiler/story-compiler/translate/stmt/statements.ts +145 -0
  63. package/src/compiler/story-compiler/translate.ts +15 -0
  64. package/src/compiler/story-compiler.ts +119 -0
  65. package/src/config/index.ts +15 -0
  66. package/src/config/manifest-read.ts +26 -0
  67. package/src/config/state-type.ts +85 -0
  68. package/src/config/story-config.ts +113 -0
  69. package/src/const-eval/config-eval.ts +181 -0
  70. package/src/const-eval/const-eval-pass.ts +133 -0
  71. package/src/const-eval/const-eval.ts +114 -0
  72. package/src/const-eval/const-expr.ts +358 -0
  73. package/src/const-eval/contracts.ts +31 -0
  74. package/src/const-eval/define-merge.ts +195 -0
  75. package/src/const-eval/diag/compare.ts +39 -0
  76. package/src/const-eval/diag/index.ts +5 -0
  77. package/src/const-eval/diag/locate.ts +45 -0
  78. package/src/const-eval/index.ts +44 -0
  79. package/src/const-eval/module-characters.ts +353 -0
  80. package/src/const-eval/module-define.ts +300 -0
  81. package/src/const-eval/round/evaluate.ts +149 -0
  82. package/src/const-eval/round/index.ts +4 -0
  83. package/src/const-eval/round/source.ts +134 -0
  84. package/src/const-eval/state-schema.ts +269 -0
  85. package/src/discovery/index.ts +7 -0
  86. package/src/discovery/source-discovery.ts +193 -0
  87. package/src/emit/compile-roundtrip.ts +45 -0
  88. package/src/emit/emit.ts +147 -0
  89. package/src/emit/index.ts +9 -0
  90. package/src/emit/report.ts +29 -0
  91. package/src/fonts/font-registry.ts +53 -0
  92. package/src/fonts/index.ts +7 -0
  93. package/src/index.ts +76 -0
  94. package/src/pipeline/gates.ts +107 -0
  95. package/src/pipeline/index.ts +18 -0
  96. package/src/pipeline/orchestrate.ts +459 -0
  97. package/src/pipeline/watch.ts +244 -0
  98. package/src/shared/errors.ts +2 -0
  99. package/src/shared/index.ts +11 -0
  100. package/src/shared/texts.ts +85 -0
  101. package/src/shared/walk-files.ts +18 -0
  102. package/src/typegen/collect.ts +107 -0
  103. package/src/typegen/font-render.ts +30 -0
  104. package/src/typegen/index.ts +18 -0
  105. package/src/typegen/render.ts +68 -0
  106. package/src/typegen/script-render.ts +21 -0
  107. package/src/typegen/state-enum-ast.ts +365 -0
  108. package/src/typegen/state-render.ts +242 -0
  109. package/src/typegen/types.ts +21 -0
  110. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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 purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the 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 owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 MoFeng-02
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `lingfan-stories-build` 可执行入口(bin 垫片,Node 直接执行)。
4
+ *
5
+ * 为什么需要这层垫片:本包以 TypeScript 源码出口(`exports` 指向 `./src/*.ts`),
6
+ * 而 Node 的类型擦除**拒绝加载 node_modules 里的 .ts**(ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING)
7
+ * ——装了本包的工程既不能 `node` 直跑 `src/cli/cli.ts`,也不该被迫装一整套构建链。
8
+ * 这层垫片用本包自带依赖 `tsx` 装载真实 CLI,转调 `runBuildCli`,呈现逻辑仍然只有一份。
9
+ *
10
+ * 用法:`lingfan-stories-build [工程根]`;缺省工程根 = 工作目录(可由 DSH_STORIES_ROOT 覆盖)。
11
+ */
12
+ import { tsImport } from "tsx/esm/api";
13
+
14
+ const { runBuildCli } = await tsImport("../src/cli/cli.ts", import.meta.url);
15
+ const code = await runBuildCli(process.argv.slice(2));
16
+ if (code !== 0) process.exit(code);
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `lingfan-stories-watch` 可执行入口(bin 垫片,Node 直接执行)。
4
+ *
5
+ * 与 `stories-build.mjs` 同一层理由:本包以 TypeScript 源码出口,而 Node 的类型擦除拒绝
6
+ * 加载 node_modules 里的 .ts;垫片用本包自带依赖 `tsx` 装载真实 CLI,转调 `startWatchCli`。
7
+ *
8
+ * 用法:`lingfan-stories-watch [工程根]`;缺省工程根 = 工作目录(可由 DSH_STORIES_ROOT 覆盖)。
9
+ */
10
+ import { tsImport } from "tsx/esm/api";
11
+
12
+ const { startWatchCli } = await tsImport(
13
+ "../src/cli/watch-cli.ts",
14
+ import.meta.url,
15
+ );
16
+ await startWatchCli(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@lingfan-engine/stories-build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "type": "module",
5
+ "description": "Stories 创作链编译包:把 Stories.src 的多目录原生 TS 源编译成 Resources/Stories/** + project.json,并产出 cell 注册生成物",
6
+ "license": "Apache-2.0",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./authoring": "./src/authoring.d.ts",
10
+ "./cell": "./src/cell/index.ts",
11
+ "./cli": "./src/cli/cli.ts",
12
+ "./watch": "./src/pipeline/watch.ts",
13
+ "./watch-cli": "./src/cli/watch-cli.ts"
14
+ },
15
+ "bin": {
16
+ "lingfan-stories-build": "./bin/stories-build.mjs",
17
+ "lingfan-stories-watch": "./bin/stories-watch.mjs"
18
+ },
19
+ "files": [
20
+ "src",
21
+ "bin",
22
+ "!src/**/*.test.ts"
23
+ ],
24
+ "sideEffects": false,
25
+ "dependencies": {
26
+ "@lingfan-engine/core": "^0.1.2",
27
+ "@lingfan-engine/editor": "^0.1.2",
28
+ "esbuild": "^0.28.2",
29
+ "tsx": "^4.23.15",
30
+ "typescript": "~6.0.3"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/MoFeng-02/LingFan.Engine.git",
35
+ "directory": "packages/stories-build"
36
+ },
37
+ "homepage": "https://github.com/MoFeng-02/LingFan.Engine#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/MoFeng-02/LingFan.Engine/issues"
40
+ },
41
+ "keywords": [
42
+ "narrative",
43
+ "build",
44
+ "story-compiler",
45
+ "typescript"
46
+ ],
47
+ "engines": {
48
+ "node": ">=22.12.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
6
53
  }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 源侧创作垫片(随包 .d.ts)
3
+ * 三组声明,各管一件事:
4
+ *
5
+ * - `state`:编译器保留根,按名匹配(assign/expr 的 stateRoot),不产生绑定。
6
+ * 此处给宽索引签名(StateRoot),保证未接 gen 类型面的工程 tsc 通过;精确类型面
7
+ * 由构建产物 `gen/state.gen.d.ts` 从 config 合并树生成,工程桥文件
8
+ * `import type { StoryState } from …/gen/state.gen` 后按名挂根(形态 A 亦可用
9
+ * `InferStateSchema<typeof state>` 静态推导)。宽 StateRoot 仅为该桥缺省前的回退。
10
+ * - `jump`:真身通道 = `@lingfan-engine/editor` 词汇层词(词表出口 + emitWordCommand 特判
11
+ * → emitJump);本声明只为 IDE/类型检查补齐,不改变运行时通道。
12
+ * - `define` / `defineVars`:config.ts 构建期内建(求值环境注入,无运行时实体);
13
+ * 全局声明供 config.ts 书写与 tsc 通过。
14
+ * - `StoriesConfig`:config.ts default 对象形态的类型(declare global,零 import 全局可用);
15
+ * `satisfies StoriesConfig` 给 default 导出强校验与 IDE 键名补全。
16
+ */
17
+ import type { StoryCommand } from "@lingfan-engine/core";
18
+
19
+ export interface StateRoot {
20
+ // 宽索引签名是未接 gen 桥工程的缺省回退:gen/state.gen.d.ts 已提供精确 StoryState,
21
+ // 桥文件引它后本接口即不参与;回退存在是为了「还没写桥」的消费工程能直接写
22
+ // state.player.gold += 20,unknown 做不到这一点。
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
+ [key: string]: any;
25
+ }
26
+
27
+ export declare const state: StateRoot;
28
+
29
+ export declare function jump(target: string | (() => void)): StoryCommand;
30
+
31
+ declare global {
32
+ /** 形态 B:点路径或对象字面量声明初始 defines(构建期累积;同键二次定义 fail-closed)。 */
33
+ function define(path: string, value: unknown): void;
34
+ function define(spec: Record<string, unknown>): void;
35
+ /** 变量键声明:返回实参本身(键 = 插值键注册表的 defineKeys 域贡献)。 */
36
+ function defineVars<T extends Record<string, string>>(spec: T): T;
37
+
38
+ /** config.ts default 对象的键契约(folders/start 必需;version/vars/state 可缺省)。 */
39
+ interface StoriesConfig {
40
+ /** 嗯,这个是你故事的目录,我让它支持你可以这样一个扫递归,也支持多目录,看你自己需要 */
41
+ readonly folders: readonly string[];
42
+ /** 这个是你需要启动的故事,注意它对应的是你 `export default function 我是故事名称` 的这个我是故事名称,哦,这个名字你自己取 */
43
+ readonly start: string;
44
+ /** 顾名思义版本 */
45
+ readonly version?: number;
46
+ /** 这个是你需要注册的变量键,注意它对应的是你 `defineVars` 的这个 defineVars,你也可以defineVars */
47
+ readonly vars?: Record<string, string>;
48
+ /** 这个是你需要注册的状态,注意它对应的是你 `state` 的这个 state,你也可以define,都可以的 */
49
+ readonly state?: Record<string, unknown>;
50
+ }
51
+ }
@@ -0,0 +1,12 @@
1
+ /** cell 声明提取失败(带 `origin` 定位:`相对路径:行`)——由调用方决定是否中断构建 */
2
+ export class CellExtractError extends Error {
3
+ /** 定位:`相对路径:行`,由构造参数赋值 */
4
+ readonly origin: string;
5
+
6
+ /** 文案拼装:定位前置成「`相对路径:行` —— 消息」,日志一眼看到出处。 */
7
+ constructor(message: string, origin: string) {
8
+ super(`${origin} —— ${message}`);
9
+ this.origin = origin;
10
+ this.name = "CellExtractError";
11
+ }
12
+ }
@@ -0,0 +1,127 @@
1
+ import * as ts from "typescript";
2
+ import type { CellIssue, FileImports } from "./types.ts";
3
+
4
+ /**
5
+ * 字面量内自由标识符校验:全部 Identifier 必须 ∈(参数、内部声明、导入绑定与全局白名单的并集),
6
+ * 属性位置(`ctx.get` 的 `get`)不算自由标识符。flat 集(不做作用域链——影子同名属
7
+ * 已注记的伪接受边界,v1 不为它上作用域机)。
8
+ */
9
+ export function checkFreeIdentifiers(
10
+ impl: ts.Node,
11
+ origin: string,
12
+ importedNames: ReadonlySet<string>,
13
+ globalWhitelist: ReadonlySet<string>,
14
+ issues: CellIssue[],
15
+ ): void {
16
+ const allowed = new Set<string>([...globalWhitelist, ...importedNames]);
17
+ const free = new Set<string>();
18
+ const visit = (node: ts.Node): void => {
19
+ // 声明与参数:名字进 allowed,继续递归初始化/函数体
20
+ if (ts.isParameter(node) || ts.isVariableDeclaration(node)) {
21
+ if (ts.isIdentifier(node.name)) allowed.add(node.name.text);
22
+ } else if (
23
+ ts.isFunctionDeclaration(node) ||
24
+ ts.isClassDeclaration(node) ||
25
+ ts.isMethodDeclaration(node)
26
+ ) {
27
+ if (node.name !== undefined && ts.isIdentifier(node.name))
28
+ allowed.add(node.name.text);
29
+ }
30
+ if (ts.isIdentifier(node)) {
31
+ const parent = node.parent;
32
+ const isPropertyName =
33
+ parent !== undefined &&
34
+ ((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
35
+ (ts.isQualifiedName(parent) && parent.right === node) ||
36
+ (ts.isPropertyAssignment(parent) && parent.name === node));
37
+ if (!isPropertyName && !allowed.has(node.text)) free.add(node.text);
38
+ }
39
+ node.forEachChild(visit);
40
+ };
41
+ visit(impl);
42
+ if (free.size > 0) {
43
+ issues.push({
44
+ message: `cell 内联实现引用了未导入的标识符(${[...free].map((n) => `"${n}"`).join("、")})——把实现提为 import,或内联其依赖(不做传递闭包)`,
45
+ origin,
46
+ });
47
+ }
48
+ }
49
+
50
+ /** 节点所在行号(1 起;读取 AST 只做定位,不改变任何判定) */
51
+ export function lineOf(sf: ts.SourceFile, node: ts.Node): number {
52
+ return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
53
+ }
54
+
55
+ /**
56
+ * 相对说明符重写:源文件(相对 Stories.src 的目录 `fromDir`)→ 生成物(`gen/`,恰深一层)。
57
+ * 解析到 Stories.src 内的规范相对路径后加 `../` 前缀;越出根 = null(调用方 fail-closed);
58
+ * 裸说明符(包名)原样。
59
+ */
60
+ export function adjustSpecifier(
61
+ specifier: string,
62
+ fromDir: string,
63
+ ): string | null {
64
+ if (!specifier.startsWith("./") && !specifier.startsWith("../"))
65
+ return specifier;
66
+ const segments: string[] = [];
67
+ for (const part of `${fromDir}/${specifier}`.split("/")) {
68
+ if (part === "" || part === ".") continue;
69
+ if (part === "..") {
70
+ if (segments.pop() === undefined) return null; // 越出 Stories.src 根
71
+ continue;
72
+ }
73
+ segments.push(part);
74
+ }
75
+ if (segments.length === 0) return null;
76
+ return `../${segments.join("/")}`;
77
+ }
78
+
79
+ /** 文件顶层 import 声明 → 绑定名集 + 「按 gen/ 位置重写过」的语句文本 */
80
+ export function collectFileImports(
81
+ sf: ts.SourceFile,
82
+ text: string,
83
+ fromDir: string,
84
+ issues: CellIssue[],
85
+ relPath: string,
86
+ ): FileImports {
87
+ const statements: Array<{ adjustedText: string; bindings: string[] }> = [];
88
+ const bindingNames = new Set<string>();
89
+ for (const statement of sf.statements) {
90
+ if (!ts.isImportDeclaration(statement)) continue;
91
+ const bindings: string[] = [];
92
+ const clause = statement.importClause;
93
+ if (clause !== undefined) {
94
+ if (clause.name !== undefined) bindings.push(clause.name.text); // import X from
95
+ const named = clause.namedBindings;
96
+ if (named !== undefined && ts.isNamedImports(named)) {
97
+ for (const element of named.elements) bindings.push(element.name.text);
98
+ }
99
+ if (named !== undefined && ts.isNamespaceImport(named)) {
100
+ bindings.push(named.name.text); // import * as X
101
+ }
102
+ }
103
+ for (const binding of bindings) bindingNames.add(binding);
104
+ // 说明符重写(生成物在 gen/,比源文件深一层)
105
+ const raw = statement.moduleSpecifier;
106
+ let adjustedText = text.slice(statement.getStart(sf), statement.getEnd());
107
+ if (ts.isStringLiteralLike(raw)) {
108
+ const adjusted = adjustSpecifier(raw.text, fromDir);
109
+ if (adjusted === null) {
110
+ issues.push({
111
+ message: `cell 所在文件 import "${raw.text}" 越出 Stories.src——生成物无法搬运该导入`,
112
+ origin: `${relPath}:${lineOf(sf, statement)}`,
113
+ });
114
+ continue;
115
+ }
116
+ if (adjusted !== raw.text) {
117
+ const rawQuoted = text.slice(raw.getStart(sf), raw.getEnd());
118
+ adjustedText = adjustedText.replace(
119
+ rawQuoted,
120
+ JSON.stringify(adjusted),
121
+ );
122
+ }
123
+ }
124
+ statements.push({ adjustedText, bindings });
125
+ }
126
+ return { bindingNames, statements };
127
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * cell 声明提取器出口(唯一出口):把 `Stories.src/**` 树里的 `cell("name", impl)` 调用
3
+ * 扫成生成注册物所需的实现文本与导入搬运集,流水线(包内 `pipeline` 域)只从这里取。
4
+ *
5
+ * 「名字在数据、实现在代码、build 做名字闭合」的提取半边。规则硬点:
6
+ * - 实现三形态:箭头/函数字面量(原文落生成物)、标识符引用、成员访问引用;
7
+ * **调用表达式(参数固化)= L2,v1 显式不支持**;
8
+ * - 字面量内自由标识符必须 ∈(所在文件导入绑定、函数参数、内部声明与标准全局的并集),
9
+ * 引用模块级本地 const = fail-closed(**不做传递闭包**——规则简单才可靠);
10
+ * - 身份键 = (face, name)、指纹 = 实现文本 trim:**同键同纹去重、同键异纹冲突**
11
+ * (fail-closed 带两处定位,不隐式覆盖);
12
+ * - face v1 恒 `guards`;`cell` 只认裸标识符调用(house style 解构导入);
13
+ * - **导入搬运按生成物位置重写相对说明符**:生成物在 `Stories.src/gen/`(比源文件
14
+ * 深一层),`"./x"`/`"../x"` 必须换算到同一目标——越出 `Stories.src` 根 fail-closed。
15
+ */
16
+
17
+ /** cell 声明提取失败(带 `origin` 定位:`相对路径:行`)——由调用方决定是否中断构建 */
18
+ export { CellExtractError } from "./errors.ts";
19
+ /** 单文件扫描:`cell(...)` 三类实现形态判定与逐条 fail-closed 文案 */
20
+ export { rootIdentifier, scanFile } from "./scan-file.ts";
21
+ /** 全树扫描:去重、指纹冲突、导入搬运 */
22
+ export { scanCells } from "./scan-cells.ts";
23
+ /** 生成物渲染(文本逐字节确定) */
24
+ export { renderFunRegister } from "./render-register.ts";
25
+ /** 标准全局白名单(16 项),供调用方比对或拼接自己的白名单 */
26
+ export { DEFAULT_GLOBAL_WHITELIST } from "./whitelist.ts";
27
+ /** 提取产出、问题与可配置项的形状 */
28
+ export type {
29
+ CellIssue,
30
+ CellScan,
31
+ FileImports,
32
+ ScanCellsOptions,
33
+ } from "./types.ts";
@@ -0,0 +1,33 @@
1
+ import type { CellScan } from "./types.ts";
2
+
3
+ /** 生成物渲染(逐字节确定:同扫描同文本;入库文件,手改会被覆盖) */
4
+ export function renderFunRegister(scan: CellScan): string {
5
+ const lines: string[] = [];
6
+ lines.push(
7
+ "/* GENERATED by stories:build (cell) — 手改会在下次构建被覆盖 */",
8
+ );
9
+ // Record<string, GuardFn> 给字面量参数提供语境类型(strict 下无 implicit-any)
10
+ lines.push('import type { GuardFn } from "@lingfan-engine/core";');
11
+ for (const statement of scan.importStatements) lines.push(statement);
12
+ lines.push("");
13
+ lines.push(
14
+ "/** 故事源 cell 提取出的具名守卫注册表:宿主 `import { guards }` 直接传给引擎,零手写接入。 */",
15
+ );
16
+ lines.push("export const guards: Record<string, GuardFn> = {");
17
+ for (const guardEntry of scan.guards) {
18
+ lines.push(` ${JSON.stringify(guardEntry.name)}: ${guardEntry.implText},`);
19
+ }
20
+ lines.push("};");
21
+ lines.push("");
22
+ lines.push(
23
+ "/** 守卫名的构建期登记处:故事源 `guard(name)` 引用了未登记的名字会在类型期报错。 */",
24
+ );
25
+ lines.push('declare module "@lingfan-engine/editor" {');
26
+ lines.push(" interface GuardNameRegistry {");
27
+ for (const guardEntry of scan.guards) {
28
+ lines.push(` ${JSON.stringify(guardEntry.name)}: 1;`);
29
+ }
30
+ lines.push(" }");
31
+ lines.push("}");
32
+ return `${lines.join("\n")}\n`;
33
+ }
@@ -0,0 +1,63 @@
1
+ import { scanFile } from "./scan-file.ts";
2
+ import type { CellIssue, CellScan, ScanCellsOptions } from "./types.ts";
3
+ import { DEFAULT_GLOBAL_WHITELIST } from "./whitelist.ts";
4
+
5
+ /**
6
+ * 全树扫描 + 聚合去重/冲突(输入 = 相对路径 → 文本;不含 gen/,由调用方过滤)。
7
+ * 同名同实现合并为一条;同名不同实现按冲突 fail-closed(不隐式覆盖)。
8
+ * `options.globalWhitelist` 缺省 = 标准全局白名单,给别的名字要显式注入。
9
+ */
10
+ export function scanCells(
11
+ files: ReadonlyMap<string, string>,
12
+ options: ScanCellsOptions = {},
13
+ ): { errors: CellIssue[]; scan: CellScan } {
14
+ const globalWhitelist = options.globalWhitelist ?? DEFAULT_GLOBAL_WHITELIST;
15
+ const issues: CellIssue[] = [];
16
+ const byName = new Map<
17
+ string,
18
+ { name: string; implText: string; origin: string }
19
+ >();
20
+ const importsInOrder: string[] = [];
21
+ const seenImports = new Set<string>();
22
+
23
+ for (const [relPath, text] of files) {
24
+ for (const found of scanFile(relPath, text, globalWhitelist, issues)) {
25
+ const existing = byName.get(found.name);
26
+ if (existing === undefined) {
27
+ byName.set(found.name, {
28
+ name: found.name,
29
+ implText: found.implText,
30
+ origin: `${relPath} (cell "${found.name}")`,
31
+ });
32
+ } else if (existing.implText.trim() !== found.fingerprint) {
33
+ issues.push({
34
+ message: `cell "${found.name}" 同名不同实现(冲突)——换名字或统一实现(已有:${existing.origin})`,
35
+ origin: `${relPath} (cell "${found.name}")`,
36
+ });
37
+ }
38
+ // 导入搬运:该 cell 所在文件中「声明了实现文本引用到的绑定」的语句(词边界匹配)
39
+ const needed = [...found.imports.bindingNames].filter((binding) =>
40
+ new RegExp(`\\b${binding}\\b`).test(found.implText),
41
+ );
42
+ for (const statement of found.imports.statements) {
43
+ if (!statement.bindings.some((binding) => needed.includes(binding)))
44
+ continue;
45
+ if (!seenImports.has(statement.adjustedText)) {
46
+ seenImports.add(statement.adjustedText);
47
+ importsInOrder.push(statement.adjustedText);
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ return {
54
+ errors: issues,
55
+ scan: {
56
+ guards: [...byName.values()].map(({ name, implText }) => ({
57
+ name,
58
+ implText,
59
+ })),
60
+ importStatements: importsInOrder,
61
+ },
62
+ };
63
+ }