@lincyaw/compiler 1.0.0-rc.32 → 1.0.0-rc.34

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/compiler",
3
- "version": "1.0.0-rc.32",
3
+ "version": "1.0.0-rc.34",
4
4
  "description": "Presmium's compiler: structured JSON documents to runtime IR, plugin loading, compile-time execution and its cache, checks and the renderers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,11 +34,10 @@
34
34
  "jiti": "^2.7.0",
35
35
  "myst-common": "1.10.1",
36
36
  "myst-transforms": "1.3.51",
37
- "resolve.exports": "2.0.4",
38
37
  "semver": "^7.8.5",
39
38
  "send": "1.2.1",
40
39
  "yaml": "^2.9.1",
41
- "@lincyaw/kernel": "1.0.0-rc.32"
40
+ "@lincyaw/kernel": "1.0.0-rc.34"
42
41
  },
43
42
  "devDependencies": {
44
43
  "@types/content-disposition": "^0.5.9",
package/src/compiler.ts CHANGED
@@ -319,7 +319,7 @@ export class Compiler {
319
319
  return { workspace, headmatter, lang, plugins, configOf, service, execute, inputs, findings, report, at, signal: options.signal, document, rawSource: read }
320
320
  }
321
321
 
322
- /** Registers each plugin's directives, roles, anchor resolvers, executors, environment providers and components. */
322
+ /** Collects the plugins' anchor resolvers, executors, environment providers and components. */
323
323
  async #collectContributions(run: CompileRun): Promise<Contributions> {
324
324
  const { plugins, configOf, execute, report, at } = run
325
325
  const resolvers = createAnchorResolverRegistry()
@@ -1,6 +1,6 @@
1
1
  import { captionSourceFingerprint, documentColorValue, isRecord, voiceTarget } from '@lincyaw/kernel'
2
- import type { CodeNode, ComponentNode, Definition, DocumentBlock, Finding, InlineNode, IRBlock, IRSection, JsonObject, MdastNode, NarrationNode, RichTextNode, SourcePos, TeachingDocument, TextStyle, VisualState } from '@lincyaw/kernel'
3
- import { relative, resolve, sep } from 'node:path'
2
+ import type { CodeNode, ComponentNode, DocumentBlock, Finding, InlineNode, IRBlock, IRSection, JsonObject, MdastNode, NarrationNode, RichTextNode, SourcePos, TeachingDocument, TextStyle, VisualState } from '@lincyaw/kernel'
3
+ import { resolve } from 'node:path'
4
4
 
5
5
  const pointerKey = (id: string) => id.replaceAll('~', '~0').replaceAll('/', '~1')
6
6
  const source = (entry: string, pointer: string): SourcePos => ({ file: entry, line: 1, format: 'json', pointer })
@@ -30,7 +30,6 @@ export function lowerDocument(doc: TeachingDocument, entry: string, deckDir: str
30
30
  const stateIndex = definition?.states.findIndex(state => state.id === visual?.state) ?? -1
31
31
  const local = stateIndex < 0 ? 0 : definition!.states[stateIndex]!.legacyIndex ?? stateIndex
32
32
  const parameters = { ...block.type === 'component' ? block.parameters : {}, ...visual?.parameters }
33
- if (definition && isMotionScene(definition)) delete parameters.scene
34
33
  return { visible: visual?.visible ?? false, localStep: block.type === 'code' ? stepIndex : local, ...visual?.state !== undefined ? { state: visual.state } : {}, ...block.type === 'component' || visual?.parameters ? { parameters } : {} }
35
34
  })
36
35
  const visible = stepStates.flatMap((state, at) => state.visible ? [at] : [])
@@ -68,8 +67,8 @@ export function lowerDocument(doc: TeachingDocument, entry: string, deckDir: str
68
67
  const definition = doc.definitions[block.definitionId]!
69
68
  const implementation = definition.implementation
70
69
  const data = definition.data ?? {}
71
- const plugin = typeof data.plugin === 'string' ? data.plugin : implementation.type === 'plugin' ? implementation.plugin : isMotionScene(definition) ? 'presmium.motion' : 'deck'
72
- const name = typeof data.name === 'string' ? data.name : implementation.type === 'plugin' ? implementation.name : isMotionScene(definition) ? 'PmScene' : `presmium-definition:${definition.id}`
70
+ const plugin = typeof data.plugin === 'string' ? data.plugin : implementation.type === 'plugin' ? implementation.plugin : 'deck'
71
+ const name = typeof data.name === 'string' ? data.name : implementation.type === 'plugin' ? implementation.name : `presmium-definition:${definition.id}`
73
72
  const node: ComponentNode = { type: 'component', plugin, name, props: { ...block.parameters }, ...block.children ? { children: block.children.map(child) } : {} }
74
73
  if (Array.isArray(data.durations) && data.durations.every(value => typeof value === 'number')) node.durations = data.durations
75
74
  if (isRecord(data.fallback) && typeof data.fallback.type === 'string') node.fallback = structuredClone(data.fallback) as MdastNode
@@ -79,14 +78,7 @@ export function lowerDocument(doc: TeachingDocument, entry: string, deckDir: str
79
78
  if (implementation.type === 'file') {
80
79
  const file = resolve(deckDir, implementation.path)
81
80
  watch(file)
82
- if (isMotionScene(definition)) {
83
- if (implementation.exportName && implementation.exportName !== 'default') report({ checkId: 'presmium.document', severity: 'error', message: 'Motion scene files currently require their default export.', source: where })
84
- const path = relative(deckDir, file).split(sep).join('/')
85
- const scene = /^scenes\/([\w-]+(?:\/[\w-]+)*)\.(?:ts|js|mjs)$/.exec(path)?.[1]
86
- if (scene) node.props.scene = scene
87
- else report({ checkId: 'presmium.document', severity: 'error', message: 'A motion scene implementation must be a supported file below scenes/.', source: where })
88
- }
89
- node.definition = { file, language: typeof data.language === 'string' ? data.language : /\.[cm]?tsx?$/.test(file) ? 'typescript' : 'javascript', ...implementation.exportName !== undefined ? { exportName: implementation.exportName } : {} }
81
+ node.definition = { file, kind: definition.kind, language: typeof data.language === 'string' ? data.language : /\.[cm]?tsx?$/.test(file) ? 'typescript' : 'javascript', ...implementation.exportName !== undefined ? { exportName: implementation.exportName } : {} }
90
82
  }
91
83
  if (implementation.type === 'module') report({ checkId: 'presmium.document', severity: 'error', message: 'Module component implementations are not available in the current document runtime; use a project file or a registered plugin component.', source: where })
92
84
  return node
@@ -117,10 +109,6 @@ export function lowerDocument(doc: TeachingDocument, entry: string, deckDir: str
117
109
  })
118
110
  }
119
111
 
120
- function isMotionScene(definition: Definition): boolean {
121
- return definition.kind === 'scene' && definition.implementation.type === 'file' && (!definition.data?.plugin || definition.data.plugin === 'presmium.motion') && (!definition.data?.name || definition.data.name === 'PmScene')
122
- }
123
-
124
112
  function styled(node: MdastNode, style: TextStyle | undefined): MdastNode {
125
113
  if (!style) return node
126
114
  const properties: Record<string, string> = {}
package/src/index.ts CHANGED
@@ -6,8 +6,6 @@ export { Compiler, DECK_ENTRY, resolveEntry, sortFindings, workspacePlugins } fr
6
6
  export type { Compilation, CompileOptions, CompilerOptions, DocumentNodeServices } from './compiler.ts'
7
7
  export { dev } from './dev.ts'
8
8
  export type { DevOptions, DevServers } from './dev.ts'
9
- export { BUILTIN_DIRECTIVE_INFO, COMMON_DIRECTIVE_OPTIONS, RUN_OPTION } from './directives.ts'
10
- export type { DirectiveInfo, DirectiveOptionInfo } from './directives.ts'
11
9
  export type { RunStats } from './execute.ts'
12
10
  export type { GitRead } from './inputs.ts'
13
11
  export { pluginLogger } from './logging.ts'
package/src/plugins.ts CHANGED
@@ -3,10 +3,10 @@ import { readdir, readFile } from 'node:fs/promises'
3
3
  import { dirname, isAbsolute, join, resolve } from 'node:path'
4
4
  import { fileURLToPath, pathToFileURL } from 'node:url'
5
5
  import { errorMessage, isRecord, kernelIncompatibility } from '@lincyaw/kernel'
6
+ import { packageExport } from '@lincyaw/kernel/node'
6
7
  import type { PresmiumNodePlugin, Severity } from '@lincyaw/kernel'
7
8
  import { createJiti } from 'jiti'
8
9
  import { satisfies, validRange } from 'semver'
9
- import { exports as resolveExports } from 'resolve.exports'
10
10
 
11
11
  export const NODE_PLUGIN_EXPORT = './presmium'
12
12
 
@@ -133,7 +133,7 @@ async function loadFrom(name: string, dir: string, problem: (severity: Severity,
133
133
  const label = typeof pkg.name === 'string' ? ` (${pkg.name}${typeof pkg.version === 'string' ? ` ${pkg.version}` : ''})` : ''
134
134
  return { problem: problem('error', `plugin "${name}"${label} is not loaded: ${peers}`) }
135
135
  }
136
- const target = exportTarget(pkg, dir)
136
+ const target = packageExport(pkg, dir, NODE_PLUGIN_EXPORT)
137
137
  if (!target) return { loaded: { name, dir } }
138
138
  const file = fileURLToPath(new URL(target, pathToFileURL(`${dir}/`)))
139
139
  if (!existsSync(file)) {
@@ -204,35 +204,9 @@ export function findPackageDir(name: string, from: string, up = true): string |
204
204
  }
205
205
  }
206
206
 
207
- function exportTarget(pkg: PluginPackage, dir: string): string | undefined {
208
- let targets: string[] | void
209
- try {
210
- targets = resolveExports(pkg, NODE_PLUGIN_EXPORT)
211
- } catch {
212
- // A package with no matching Node export still contributes its components.
213
- return undefined
214
- }
215
- if (!targets?.length) return undefined
216
- const base = pathToFileURL(`${dir}/`)
217
- for (const target of targets) {
218
- const path = target.split(/[?#]/, 1)[0]!
219
- if (!path.startsWith('./') || /%2f|%5c/i.test(path)) continue
220
- try {
221
- const segments = path.slice(2).split(/[\\/]/).map(decodeURIComponent)
222
- if (segments.some(segment => /^(?:\.{1,2}|node_modules)$/i.test(segment))) continue
223
- const normalized = new URL(target, base)
224
- if (!normalized.href.startsWith(base.href)) continue
225
- return target
226
- } catch {
227
- // Invalid URL encoding cannot name a package file; arrays may provide another target.
228
- }
229
- }
230
- throw new Error(`${NODE_PLUGIN_EXPORT} has no valid package-relative Node target`)
231
- }
232
-
233
207
  function isNodePlugin(value: unknown): value is PresmiumNodePlugin {
234
208
  if (!isRecord(value) || typeof value.id !== 'string') return false
235
- const lists = ['resolvers', 'checks', 'directives', 'passes', 'executors', 'roles', 'tools'] as const
209
+ const lists = ['resolvers', 'checks', 'passes', 'executors', 'tools'] as const
236
210
  const renderer = value.renderer
237
211
  return lists.every(key => value[key] === undefined || Array.isArray(value[key]))
238
212
  && ['version', 'kernel'].every(key => value[key] === undefined || typeof value[key] === 'string')
package/src/directives.ts DELETED
@@ -1,117 +0,0 @@
1
- import type { DirectiveOptionType, Locale } from '@lincyaw/kernel'
2
-
3
- export interface DirectiveOptionInfo {
4
- type?: DirectiveOptionType
5
- doc?: Record<Locale, string>
6
- values?: string[]
7
- }
8
-
9
- export interface DirectiveInfo {
10
- name: string
11
- doc: Record<Locale, string>
12
- options: Record<string, DirectiveOptionInfo>
13
- }
14
-
15
- export const COMMON_DIRECTIVE_OPTIONS: Record<string, DirectiveOptionInfo> = {
16
- reveal: {
17
- doc: { 'zh-CN': '在下一步出现;`{slide}`、`{only}` 上写 `items` 时列表逐项出现。', 'en': 'Appears at the next step; `items` on `{slide}` and `{only}` reveals list items one per step.' },
18
- values: ['items'],
19
- },
20
- label: { type: 'string', doc: { 'zh-CN': '块 ID。', 'en': 'Block id.' } },
21
- audience: {
22
- type: 'string',
23
- doc: { 'zh-CN': '只给这些受众(逗号分隔),如 `teacher`;`presmium build --audience student` 不输出它。', 'en': 'Only for these audiences (comma-separated), e.g. `teacher`; `presmium build --audience student` leaves it out.' },
24
- values: ['teacher', 'student'],
25
- },
26
- }
27
-
28
- export const RUN_OPTION: DirectiveOptionInfo = {
29
- type: 'string',
30
- doc: { 'zh-CN': '`compile` 在构建时执行并录制输出,`live` 只在浏览器中执行,`both` 两者都做。', 'en': '`compile` records the output at build time, `live` runs in the browser, `both` does both.' },
31
- values: ['compile', 'live', 'both'],
32
- }
33
-
34
- const STEP_RANGE: Record<string, DirectiveOptionInfo> = {
35
- at: { type: 'number', doc: { 'zh-CN': '从指定步骤开始显示(从 0 开始),不能与 reveal 合用。', en: 'Shows from this zero-based step; cannot be combined with reveal.' } },
36
- until: { type: 'number', doc: { 'zh-CN': '到指定步骤时隐藏;回退时恢复。', en: 'Hides at this step and returns when stepping back.' } },
37
- }
38
-
39
- const TITLE = { 'zh-CN': '标题。', 'en': 'Title.' }
40
-
41
- const CODE_OPTIONS: Record<string, DirectiveOptionInfo> = {
42
- 'caption': { type: 'string', doc: TITLE },
43
- 'filename': { type: 'string', doc: TITLE },
44
- 'emphasize-lines': { type: 'string', doc: { 'zh-CN': '每一步都强调的行,如 `2, 4-5`。', 'en': 'Lines highlighted at every step, e.g. `2, 4-5`.' } },
45
- 'run': RUN_OPTION,
46
- 'executor': { type: 'string', doc: { 'zh-CN': '执行器 ID。', 'en': 'Executor id.' } },
47
- 'timeout': { type: 'number', doc: { 'zh-CN': '毫秒。', 'en': 'Milliseconds.' } },
48
- 'env': { type: 'string', doc: { 'zh-CN': '运行环境:头部 `execute.environments` 中的名字,或 `browser`。', 'en': 'Where it runs: a name of `execute.environments` in the headmatter, or `browser`.' } },
49
- 'session': { type: 'string', doc: { 'zh-CN': '执行会话:同一会话的代码块共享解释器。', 'en': 'Execution session: code blocks of one session share the interpreter.' } },
50
- 'echo': { type: 'string', doc: { 'zh-CN': '`false`:只显示输出,Markdown 输出按正文显示。', 'en': '`false`: only the output shows, Markdown output as prose.' }, values: ['false'] },
51
- }
52
-
53
- const CLASS: DirectiveOptionInfo = { type: 'string', doc: { 'zh-CN': 'CSS 类名。', 'en': 'CSS class names.' } }
54
-
55
- const LAYOUT_DIRECTIVES: DirectiveInfo[] = [
56
- {
57
- name: 'grid',
58
- doc: { 'zh-CN': '栅格:参数为四档屏宽(手机、小、中、大)的列数,如 `1 1 2 3`;正文为 `{card}` 或 `{grid-item}`。', 'en': 'A grid: the argument is the columns at four screen widths (phone, small, medium, large), e.g. `1 1 2 3`; the body holds `{card}` or `{grid-item}`.' },
59
- options: { class: CLASS },
60
- },
61
- {
62
- name: 'grid-item',
63
- doc: { 'zh-CN': '栅格中的一格。', 'en': 'An item of a grid.' },
64
- options: { columns: { type: 'number', doc: { 'zh-CN': '占一行 12 份中的几份。', 'en': 'How many twelfths of a row it takes.' } }, class: CLASS },
65
- },
66
- {
67
- name: 'card',
68
- doc: { 'zh-CN': '卡片:参数为标题;正文中 `^^^` 之前为页眉,`+++` 之后为页脚。', 'en': 'A card: the argument is its title; in the body, what precedes `^^^` is its header, what follows `+++` its footer.' },
69
- options: {
70
- link: { type: 'string', doc: { 'zh-CN': '整张卡片链接到的地址。', 'en': 'Where the whole card links to.' } },
71
- header: { type: 'string', doc: { 'zh-CN': '页眉。', 'en': 'Header.' } },
72
- footer: { type: 'string', doc: { 'zh-CN': '页脚。', 'en': 'Footer.' } },
73
- },
74
- },
75
- {
76
- name: 'tab-set',
77
- doc: { 'zh-CN': '一组选项卡;正文为 `{tab-item}`。', 'en': 'A set of tabs; the body holds `{tab-item}`.' },
78
- options: { class: CLASS },
79
- },
80
- {
81
- name: 'tab-item',
82
- doc: { 'zh-CN': '一个选项卡:参数为标题。', 'en': 'A tab: the argument is its title.' },
83
- options: {
84
- sync: { type: 'string', doc: { 'zh-CN': '同步键:选中它时,页面上同一键的选项卡一起切换。', 'en': 'Sync key: choosing it switches the tabs with the same key on the page.' } },
85
- selected: { type: 'boolean', doc: { 'zh-CN': '开始时选中。', 'en': 'Selected at first.' } },
86
- },
87
- },
88
- ]
89
-
90
- export const BUILTIN_DIRECTIVE_INFO: readonly DirectiveInfo[] = [
91
- { name: 'narration', doc: { 'zh-CN': '指定步骤的讲解与字幕;正文为 MyST。', en: 'Narration and captions for one step; the body is MyST.' }, options: { at: STEP_RANGE.at!, mode: { type: 'string', values: ['during', 'after'], doc: { 'zh-CN': 'during:边放边讲;after:动画播完再讲。', en: 'during: speak with the animation; after: speak after it finishes.' } } } },
92
- { name: 'slide', doc: { 'zh-CN': '上屏内容;正文为 MyST。', 'en': 'Content shown on screen; the body is MyST.' }, options: STEP_RANGE },
93
- { name: 'only', doc: { 'zh-CN': '只在这些渲染端出现的内容,如 `{only} web, notebook`。', 'en': 'Content limited to renderers, e.g. `{only} web, notebook`.' }, options: STEP_RANGE },
94
- { name: 'hints', doc: { 'zh-CN': '各渲染端的排版提示;正文为 YAML。', 'en': 'Layout hints per renderer; the body is YAML.' }, options: {} },
95
- { name: 'config', doc: { 'zh-CN': '只在本章节生效的插件配置;正文为 YAML,键为插件 ID。', 'en': 'Plugin configuration of this section; the body is YAML keyed by plugin id.' }, options: {} },
96
- { name: 'audience', doc: { 'zh-CN': '整个章节只给这些受众,如 `{audience} teacher`;放在章节顶层,没有正文。', 'en': 'The whole section is only for these audiences, e.g. `{audience} teacher`; at the top of a section, without a body.' }, options: {} },
97
- {
98
- name: 'component',
99
- doc: { 'zh-CN': '插件组件,如 `{component} PmQuiz`;正文为 YAML 属性。', 'en': 'A plugin component, e.g. `{component} PmQuiz`; the body is YAML props.' },
100
- options: { span: { type: 'number', doc: { 'zh-CN': '内部步数。', 'en': 'Internal steps.' } }, plugin: { type: 'string', doc: { 'zh-CN': '插件 ID。', 'en': 'Plugin id.' } } },
101
- },
102
- { name: 'include', doc: { 'zh-CN': '引入另一个源文件。', 'en': 'Includes another source file.' }, options: {} },
103
- {
104
- name: 'literalinclude',
105
- doc: { 'zh-CN': '以代码显示一个文件(或其中几行);参数为文件路径。', 'en': 'Shows a file (or some of its lines) as code; the argument is the file path.' },
106
- options: {
107
- 'language': { type: 'string', doc: { 'zh-CN': '语言;默认按扩展名。', 'en': 'Language; by default from the extension.' } },
108
- 'lines': { type: 'string', doc: { 'zh-CN': '只显示这些行,如 `2, 4-6`。', 'en': 'Only these lines, e.g. `2, 4-6`.' } },
109
- 'start-after': { type: 'string', doc: { 'zh-CN': '从含这段文字的行之后开始。', 'en': 'Starts after the line with this text.' } },
110
- 'end-before': { type: 'string', doc: { 'zh-CN': '到含这段文字的行之前结束。', 'en': 'Ends before the line with this text.' } },
111
- 'caption': CODE_OPTIONS.caption!,
112
- 'emphasize-lines': CODE_OPTIONS['emphasize-lines']!,
113
- },
114
- },
115
- ...['code', 'code-block', 'code-cell', 'sourcecode'].map(name => ({ name, doc: { 'zh-CN': '代码;参数为语言。', 'en': 'Code; the argument is the language.' }, options: CODE_OPTIONS })),
116
- ...LAYOUT_DIRECTIVES,
117
- ]