clarusjs 0.19.1 → 0.20.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.
@@ -7,7 +7,7 @@ import { ClarusError } from '../compiler/errors.js';
7
7
  import { modifierError, splitEvent } from '../compiler/events.js';
8
8
  import { outerIndexIn } from '../compiler/loops.js';
9
9
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
10
- import { checkScript, providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
10
+ import { checkScript, providesIn, referencesNames, scriptAnnotations, scriptTypeImports, splitImports } from '../compiler/script.js';
11
11
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
12
12
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
13
13
  function patternNames(params) {
@@ -102,21 +102,48 @@ export function generateTs(source, file, options = {}) {
102
102
  if (options.loader)
103
103
  emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
104
104
  const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
105
- const provides = !!parsed.script && !!script && providesIn(script, file, source, parsed.script.start);
105
+ const provides = (!!parsed.script && !!script && providesIn(script, file, source, parsed.script.start))
106
+ || (!!parsed.serverScript && providesIn(splitImports(parsed.serverScript.code, file, source, parsed.serverScript.start, true), file, source, parsed.serverScript.start));
106
107
  if (parsed.script && script) {
107
108
  for (const imp of script.imports) {
108
109
  copy(imp.text, parsed.script.start + imp.start);
109
110
  emit('\n');
110
111
  }
112
+ if (parsed.script.ts) {
113
+ for (const t of [...(parsed.script.typeImports ?? []), ...(parsed.script.typeDecls ?? [])]) {
114
+ if (parsed.script.ts.startsWith(t.text, t.start))
115
+ copy(t.text, parsed.script.start + t.start);
116
+ else
117
+ emit(t.text);
118
+ emit('\n');
119
+ }
120
+ }
121
+ else
122
+ for (const line of scriptTypeImports(parsed.script.code))
123
+ emit(`${line}\n`);
111
124
  }
112
125
  const serverScript = parsed.serverScript ? splitImports(parsed.serverScript.code, file, source, parsed.serverScript.start, true) : null;
113
126
  if (parsed.serverScript && serverScript) {
127
+ if (parsed.serverScript.ts) {
128
+ for (const t of [...(parsed.serverScript.typeImports ?? []), ...(parsed.serverScript.typeDecls ?? [])]) {
129
+ if (parsed.serverScript.ts.startsWith(t.text, t.start))
130
+ copy(t.text, parsed.serverScript.start + t.start);
131
+ else
132
+ emit(t.text);
133
+ emit('\n');
134
+ }
135
+ }
136
+ else
137
+ for (const line of scriptTypeImports(parsed.serverScript.code))
138
+ emit(`${line}\n`);
114
139
  for (const imp of serverScript.imports) {
115
140
  copy(imp.text, parsed.serverScript.start + imp.start);
116
141
  emit('\n');
117
142
  }
118
143
  }
119
144
  for (const t of parsed.types) {
145
+ if (t.doc)
146
+ emit(t.doc + '\n');
120
147
  emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
121
148
  copy(t.type, t.typeStart);
122
149
  emit('\n');
@@ -125,9 +152,11 @@ export function generateTs(source, file, options = {}) {
125
152
  if (!parsed.inputs.length)
126
153
  emit(' __cl_none?: never\n');
127
154
  for (const input of parsed.inputs) {
155
+ if (input.doc)
156
+ emit(` ${input.doc}\n`);
128
157
  emit(' ');
129
158
  copy(input.name, input.nameStart);
130
- emit(input.default !== undefined ? '?: ' : ': ');
159
+ emit(input.default !== undefined || input.optional ? '?: ' : ': ');
131
160
  copy(input.type, input.typeStart);
132
161
  emit('\n');
133
162
  }
@@ -150,7 +179,13 @@ export function generateTs(source, file, options = {}) {
150
179
  }
151
180
  emit('}\n');
152
181
  if (provides)
153
- emit('declare function provide(key: string, value: unknown): void\n');
182
+ emit('declare function provide<T>(key: string | { readonly name: string; readonly __clContext?: T }, value: NoInfer<T>): void\n');
183
+ if (parsed.contexts.length)
184
+ emit('declare function __cl_context<T>(fallback?: () => T): T\n');
185
+ if (parsed.contexts.some((c) => c.key))
186
+ emit('declare function __cl_publicKey(key: { readonly public: true }): void\n');
187
+ if (parsed.contexts.some((c) => c.key))
188
+ emit('type __cl_ContextOf<K> = K extends { readonly __clContext?: infer T } ? T : unknown\n');
154
189
  if (parsed.events.length)
155
190
  emit('declare const emit: <K extends keyof Events>(name: K, ...args: Events[K] extends void ? [value?: undefined, info?: { reason?: string; event?: Event }] : [value: Events[K], info?: { reason?: string; event?: Event }]) => boolean\n');
156
191
  let loaderSpan;
@@ -180,31 +215,53 @@ export function generateTs(source, file, options = {}) {
180
215
  copy(input.name, input.nameStart);
181
216
  if (input.default !== undefined && input.defaultStart !== undefined) {
182
217
  emit(' = ');
183
- copy(input.default, input.defaultStart);
218
+ copy(input.defaultTs ?? input.default, input.defaultStart);
184
219
  }
185
220
  });
186
221
  emit(' } = __cl_props\n');
187
222
  emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
188
223
  }
224
+ if (parsed.props) {
225
+ const defaulted = parsed.inputs.filter((i) => parsed.props.keys.includes(i.name) && i.default !== undefined).map((i) => JSON.stringify(i.name));
226
+ const keys = parsed.props.keys.map((k) => JSON.stringify(k)).join(' | ') || 'never';
227
+ const d = defaulted.join(' | ') || 'never';
228
+ emit(` const ${parsed.props.name}: __cl_Readonly<Omit<Pick<Inputs, ${keys}>, ${d}> & Required<Pick<Inputs, ${d}>>> = __cl_props as any\n __cl_use(${parsed.props.name})\n`);
229
+ }
230
+ const island = (!!script && (/\S/.test(script.body) || parsed.events.length > 0)) || parsed.inputs.some((i) => i.model);
189
231
  for (const c of parsed.contexts) {
232
+ if (island && c.key) {
233
+ emit(' __cl_publicKey(');
234
+ copy(c.key, c.typeStart);
235
+ emit(')\n');
236
+ }
237
+ if (c.doc)
238
+ emit(` ${c.doc}\n`);
190
239
  emit(' const ');
191
240
  copy(c.name, c.nameStart);
192
241
  emit(': ');
193
242
  copy(c.type, c.typeStart);
194
- emit(' = ');
195
- if (c.default !== undefined && c.defaultStart !== undefined)
196
- copy(c.default, c.defaultStart);
197
- else
198
- emit('null!');
199
- emit('\n');
243
+ emit(` = __cl_context<${c.type}>(`);
244
+ if (c.default !== undefined && c.defaultStart !== undefined) {
245
+ emit('() => (');
246
+ copy(c.defaultTs ?? c.default, c.defaultStart);
247
+ emit(')');
248
+ }
249
+ emit(')\n');
200
250
  }
201
251
  if (parsed.contexts.length)
202
252
  emit(` __cl_use([${parsed.contexts.map((c) => c.name).join(', ')}])\n`);
203
253
  const copyScript = (from, split) => {
204
- const body = split.body;
254
+ let body = split.body;
255
+ const moved = from.ts ? [...(from.typeImports ?? []), ...(from.typeDecls ?? [])].filter((t) => from.ts.startsWith(t.text, t.start)) : [];
256
+ for (const [s, e] of from.factories ?? [])
257
+ moved.push({ text: from.ts.slice(s, e), start: s });
258
+ if (from.ts)
259
+ body = body.split('').map((c, i) => (c === from.code[i] ? from.ts[i] : c)).join('');
205
260
  const cuts = [
206
- ...split.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
207
- ...untypedParams(from.code).map((e) => ({ ...e, end: e.at })),
261
+ ...moved.map((t) => ({ at: t.start, end: t.start + t.text.length, text: t.text.replace(/[^\n]/g, ' ') })),
262
+ ...(from.ts ? (from.stayingExports ?? []).map((at) => ({ at, end: at + 'export'.length, text: ' ' })) : []),
263
+ ...split.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: imp.text.replace(/[^\n]/g, ' ') })),
264
+ ...(from.ts ? [] : scriptAnnotations(from.code).map((e) => ({ ...e, end: e.at }))),
208
265
  ].sort((a, b) => a.at - b.at);
209
266
  let pos = 0;
210
267
  for (const cut of cuts) {
@@ -511,6 +568,12 @@ function joinPath(dir, rel) {
511
568
  export function viewsDeclaration(views) {
512
569
  const lines = ['// Generated by clarusjs check: view name → inputs, for render() from clarusjs/views. Declarations only.'];
513
570
  const entries = [];
571
+ const modules = new Map();
572
+ const moduleAlias = (from) => {
573
+ if (!modules.has(from))
574
+ modules.set(from, `__cl_i${modules.size}`);
575
+ return modules.get(from);
576
+ };
514
577
  views.forEach(({ file, source }, i) => {
515
578
  let parsed;
516
579
  try {
@@ -521,30 +584,60 @@ export function viewsDeclaration(views) {
521
584
  }
522
585
  const ns = `__cl_v${i}`;
523
586
  const body = [];
524
- for (const t of parsed.typeImports) {
525
- const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from.startsWith('~/') ? `../src/${t.from.slice(2)}` : t.from;
587
+ const renames = new Map();
588
+ const scriptImports = [parsed.script, parsed.serverScript].flatMap((s) => s?.typeImports ?? [])
589
+ .map((imp) => /^import\s+type\s+(\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+(['"])(.+?)\2/.exec(imp.text))
590
+ .filter((m) => !!m).map((m) => ({ clause: m[1], from: m[3] }));
591
+ const fromHere = (spec) => (spec.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), spec)}` : spec.startsWith('~/') ? `../src/${spec.slice(2)}` : spec);
592
+ const scriptTypes = [parsed.script, parsed.serverScript].flatMap((s) => (s?.typeDecls ?? []).map((d) => d.text)).join('\n') + parsed.inputs.map((i) => i.type).join('\n');
593
+ for (const s of [parsed.script, parsed.serverScript]) {
594
+ if (!s?.ts)
595
+ continue;
596
+ for (const m of s.code.matchAll(/^\s*import\s+(\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+(['"])(.+?)\2/gm)) {
597
+ if (m[1].startsWith('*')) {
598
+ const local = m[1].replace(/^\*\s+as\s+/, '');
599
+ if (new RegExp(`\\btypeof\\s+${local.replace(/\$/g, '\\$')}\\b`).test(scriptTypes))
600
+ body.push(` const ${local}: typeof import(${JSON.stringify(fromHere(m[3]))})`);
601
+ continue;
602
+ }
603
+ const names = m[1].startsWith('{')
604
+ ? m[1].slice(1, -1).split(',').map((p) => p.trim()).filter(Boolean).map((p) => { const [name, local = name] = p.split(/\s+as\s+/).map((x) => x.trim()); return { name: name, local: local }; })
605
+ : [{ name: 'default', local: m[1] }];
606
+ for (const { name, local } of names)
607
+ if (new RegExp(`\\btypeof\\s+${local.replace(/\$/g, '\\$')}\\b`).test(scriptTypes))
608
+ body.push(` const ${local}: typeof import(${JSON.stringify(fromHere(m[3]))}).${name}`);
609
+ }
610
+ }
611
+ for (const t of [...parsed.typeImports, ...scriptImports]) {
612
+ const mod = moduleAlias(fromHere(t.from));
526
613
  const clause = t.clause.trim();
527
614
  if (clause.startsWith('{')) {
528
615
  for (const part of clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '')).filter(Boolean)) {
529
616
  const [name, local = name] = part.split(/\s+as\s+/).map((x) => x.trim());
530
- body.push(` type ${local} = import(${JSON.stringify(from)}).${name}`);
617
+ body.push(` import ${local} = ${mod}.${name}`);
531
618
  }
532
619
  }
533
- else if (!clause.startsWith('*')) {
534
- body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
535
- }
620
+ else if (clause.startsWith('*'))
621
+ body.push(` import ${clause.replace(/^\*\s+as\s+/, '')} = ${mod}`);
622
+ else
623
+ renames.set(clause, `${mod}.default`);
536
624
  }
625
+ for (const s of [parsed.script, parsed.serverScript])
626
+ for (const d of s?.typeDecls ?? [])
627
+ body.push(` ${d.text}`);
537
628
  for (const t of parsed.types)
538
- body.push(t.kind === 'interface' ? ` interface ${t.name}${t.params ?? ''} ${t.type}` : ` type ${t.name}${t.params ?? ''} = ${t.type}`);
629
+ body.push(...(t.doc ? [` ${t.doc}`] : []), t.kind === 'interface' ? ` interface ${t.name}${t.params ?? ''} ${t.type}` : ` type ${t.name}${t.params ?? ''} = ${t.type}`);
539
630
  body.push(` interface Inputs {`);
540
631
  if (!parsed.inputs.length)
541
632
  body.push(' __cl_none?: never');
542
633
  for (const input of parsed.inputs)
543
- body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
634
+ body.push(...(input.doc ? [` ${input.doc}`] : []), ` ${input.name}${input.default !== undefined || input.optional ? '?' : ''}: ${input.type}`);
544
635
  body.push(' }');
545
- lines.push(`declare namespace ${ns} {`, ...body, '}');
636
+ const renamed = (line) => [...renames].reduce((l, [local, to]) => l.replace(new RegExp(`(?<![\\w$.])${local.replace(/\$/g, '\\$')}(?![\\w$]|\\s*\\??:)`, 'g'), to), line);
637
+ lines.push(`declare namespace ${ns} {`, ...body.map((l) => (l.startsWith(' import ') ? l : renamed(l))), '}');
546
638
  entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.[^./]+$/, ''))}: ${ns}.Inputs`);
547
639
  });
640
+ lines.splice(1, 0, ...[...modules].map(([from, alias]) => `import * as ${alias} from ${JSON.stringify(from)}`));
548
641
  lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
549
642
  return lines.join('\n');
550
643
  }
package/dist/cli/index.js CHANGED
@@ -3,6 +3,7 @@ import { Command } from 'commander';
3
3
  import { check } from './check.js';
4
4
  import { loadProject } from './project.js';
5
5
  import { explain } from './explain.js';
6
+ import { migrateFiles } from './migrate-files.js';
6
7
  import { serve as mapper } from './mapper.js';
7
8
  import { serve } from '../node/serve.js';
8
9
  import { writeEnvTypes } from '../vite/env.js';
@@ -47,6 +48,22 @@ program
47
48
  console.log(options.json ? result.json : result.text);
48
49
  process.exitCode = result.exitCode;
49
50
  });
51
+ program
52
+ .command('migrate')
53
+ .description('move @input, @model and @event (and @type, @interface, @import type) into each component\'s <script lang="ts"> as props(), model() and events(); reads of an input become props.name. Without --write it only lists what would change')
54
+ .argument('[paths...]', '.tscl files or folders (default: src)', ['src'])
55
+ .option('--write', 'write the changed files')
56
+ .action((paths, options) => {
57
+ const result = migrateFiles(paths, !!options.write);
58
+ for (const file of result.changed)
59
+ console.log(`${options.write ? 'migrated' : 'would migrate'} ${file}`);
60
+ for (const note of result.notes)
61
+ console.log(`note: ${note}`);
62
+ if (!result.changed.length)
63
+ console.log('Nothing to migrate.');
64
+ else if (!options.write)
65
+ console.log('\nRun again with --write to change them, then clarusjs check.');
66
+ });
50
67
  program
51
68
  .command('mapper')
52
69
  .description('the TypeScript 7.1 content mapper for .tscl files (TypeScript starts it; see https://clarusjs.com/guide/editor)')
@@ -0,0 +1,5 @@
1
+ /** Each .tscl file under `paths` that migrate() would change (written with `write`), and its notes. */
2
+ export declare function migrateFiles(paths: string[], write: boolean): {
3
+ changed: string[];
4
+ notes: string[];
5
+ };
@@ -0,0 +1,22 @@
1
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { migrate } from './migrate.js';
4
+ const tsclUnder = (path) => statSync(path).isDirectory()
5
+ ? readdirSync(path).filter((n) => n !== 'node_modules' && !n.startsWith('.')).flatMap((n) => tsclUnder(join(path, n)))
6
+ : path.endsWith('.tscl') ? [path] : [];
7
+ export function migrateFiles(paths, write) {
8
+ const changed = [];
9
+ const notes = [];
10
+ for (const file of paths.flatMap(tsclUnder)) {
11
+ const source = readFileSync(file, 'utf8');
12
+ const name = relative(process.cwd(), file);
13
+ const out = migrate(source, name);
14
+ notes.push(...out.notes);
15
+ if (out.code === source)
16
+ continue;
17
+ changed.push(name);
18
+ if (write)
19
+ writeFileSync(file, out.code);
20
+ }
21
+ return { changed, notes };
22
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `source` in the script form, or unchanged when there's nothing to move. `notes` says what it left (an @context,
3
+ * which reads by name) and what may need a hand (a script that became TypeScript may need parameter types).
4
+ */
5
+ export declare function migrate(source: string, file: string): {
6
+ code: string;
7
+ notes: string[];
8
+ };
@@ -0,0 +1,293 @@
1
+ import { parse as acornParse, parseExpressionAt } from 'acorn';
2
+ import { parse } from '../compiler/parse.js';
3
+ import { compile } from '../compiler/index.js';
4
+ const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
5
+ function bindingNames(p, out = []) {
6
+ if (!p)
7
+ return out;
8
+ if (p.type === 'Identifier')
9
+ out.push(p.name);
10
+ else if (p.type === 'ObjectPattern')
11
+ for (const x of p.properties)
12
+ bindingNames(x.type === 'RestElement' ? x.argument : x.value, out);
13
+ else if (p.type === 'ArrayPattern')
14
+ for (const x of p.elements)
15
+ bindingNames(x, out);
16
+ else if (p.type === 'AssignmentPattern')
17
+ bindingNames(p.left, out);
18
+ else if (p.type === 'RestElement')
19
+ bindingNames(p.argument, out);
20
+ return out;
21
+ }
22
+ function declaredIn(body) {
23
+ return body.flatMap((s) => {
24
+ const d = s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s;
25
+ if (d.type === 'VariableDeclaration')
26
+ return d.declarations.flatMap((x) => bindingNames(x.id));
27
+ if ((d.type === 'FunctionDeclaration' || d.type === 'ClassDeclaration') && d.id)
28
+ return [d.id.name];
29
+ if (d.type === 'ImportDeclaration')
30
+ return d.specifiers.map((x) => x.local.name);
31
+ return [];
32
+ });
33
+ }
34
+ function renameReads(ast, names, shadow, offset, edits) {
35
+ const visit = (node, parent, key, scopes) => {
36
+ if (!node || typeof node.type !== 'string')
37
+ return;
38
+ const hidden = (name) => shadow.has(name) || scopes.some((s) => s.has(name));
39
+ if (node.type === 'Identifier') {
40
+ if (!names.has(node.name) || hidden(node.name))
41
+ return;
42
+ if (parent?.type === 'MemberExpression' && key === 'property' && !parent.computed)
43
+ return;
44
+ if ((parent?.type === 'Property' || parent?.type === 'MethodDefinition' || parent?.type === 'PropertyDefinition') && key === 'key' && !parent.computed)
45
+ return;
46
+ edits.push({ start: offset + node.start, end: offset + node.end, text: `props.${node.name}` });
47
+ return;
48
+ }
49
+ if (node.type === 'Property' && node.shorthand && node.value.type === 'Identifier' && names.has(node.value.name) && !hidden(node.value.name) && parent?.type === 'ObjectExpression') {
50
+ edits.push({ start: offset + node.start, end: offset + node.end, text: `${node.key.name}: props.${node.key.name}` });
51
+ return;
52
+ }
53
+ const pattern = (p, s) => {
54
+ if (!p)
55
+ return;
56
+ if (p.type === 'AssignmentPattern') {
57
+ pattern(p.left, s);
58
+ visit(p.right, p, 'right', s);
59
+ }
60
+ else if (p.type === 'ObjectPattern')
61
+ for (const x of p.properties) {
62
+ if (x.type === 'RestElement')
63
+ pattern(x.argument, s);
64
+ else {
65
+ if (x.computed)
66
+ visit(x.key, x, 'key', s);
67
+ pattern(x.value, s);
68
+ }
69
+ }
70
+ else if (p.type === 'ArrayPattern')
71
+ for (const x of p.elements)
72
+ pattern(x, s);
73
+ else if (p.type === 'RestElement')
74
+ pattern(p.argument, s);
75
+ };
76
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
77
+ const own = new Set([...node.params.flatMap((p) => bindingNames(p)), ...(node.type === 'FunctionExpression' && node.id ? [node.id.name] : [])]);
78
+ if (node.body.type === 'BlockStatement')
79
+ for (const n of declaredIn(node.body.body))
80
+ own.add(n);
81
+ const inner = [...scopes, own];
82
+ for (const p of node.params)
83
+ pattern(p, inner);
84
+ visit(node.body, node, 'body', inner);
85
+ return;
86
+ }
87
+ if (node.type === 'Program' || node.type === 'BlockStatement' || node.type === 'StaticBlock') {
88
+ const inner = [...scopes, new Set(declaredIn(node.body))];
89
+ for (const s of node.body)
90
+ visit(s, node, 'body', inner);
91
+ return;
92
+ }
93
+ if (node.type === 'VariableDeclarator') {
94
+ pattern(node.id, scopes);
95
+ if (node.init)
96
+ visit(node.init, node, 'init', scopes);
97
+ return;
98
+ }
99
+ if (node.type === 'CatchClause') {
100
+ const inner = [...scopes, new Set(bindingNames(node.param))];
101
+ visit(node.body, node, 'body', inner);
102
+ return;
103
+ }
104
+ if (node.type === 'ForStatement' || node.type === 'ForInStatement' || node.type === 'ForOfStatement') {
105
+ const head = node.type === 'ForStatement' ? node.init : node.left;
106
+ const inner = [...scopes, new Set(head?.type === 'VariableDeclaration' ? head.declarations.flatMap((x) => bindingNames(x.id)) : [])];
107
+ for (const [k, v] of Object.entries(node))
108
+ if (v && typeof v === 'object' && k !== 'loc')
109
+ visit(v, node, k, inner);
110
+ return;
111
+ }
112
+ if (node.type === 'ImportDeclaration' || node.type === 'LabeledStatement' || node.type === 'BreakStatement' || node.type === 'ContinueStatement')
113
+ return;
114
+ if ((node.type === 'ClassDeclaration' || node.type === 'ClassExpression')) {
115
+ if (node.superClass)
116
+ visit(node.superClass, node, 'superClass', scopes);
117
+ visit(node.body, node, 'body', scopes);
118
+ return;
119
+ }
120
+ for (const [k, v] of Object.entries(node)) {
121
+ if (k === 'loc' || !v || typeof v !== 'object')
122
+ continue;
123
+ for (const c of Array.isArray(v) ? v : [v])
124
+ if (c && typeof c.type === 'string')
125
+ visit(c, node, k, scopes);
126
+ }
127
+ };
128
+ visit(ast, undefined, '', []);
129
+ }
130
+ function renameInExpression(source, text, at, names, shadow, statements, edits) {
131
+ const start = source.indexOf(text, at);
132
+ if (start === -1 || !text.trim())
133
+ return;
134
+ try {
135
+ const ast = (statements ? acornParse(text, OPTS) : parseExpressionAt(text, 0, OPTS));
136
+ renameReads(ast, names, shadow, start, edits);
137
+ }
138
+ catch { }
139
+ }
140
+ const fillNames = (params) => { try {
141
+ return bindingNames(parseExpressionAt(`(${params}) => 0`, 0, OPTS).params[0]).concat(parseExpressionAt(`(${params}) => 0`, 0, OPTS).params.slice(1).flatMap((p) => bindingNames(p)));
142
+ }
143
+ catch {
144
+ return [];
145
+ } };
146
+ function renameInTemplate(source, nodes, names, shadow, edits) {
147
+ for (const n of nodes) {
148
+ if (n.type === 'expr')
149
+ renameInExpression(source, n.expr, n.start, names, shadow, false, edits);
150
+ else if (n.type === 'element') {
151
+ for (const a of n.attrs) {
152
+ if (a.kind === 'interp') {
153
+ for (const p of a.parts)
154
+ if (typeof p !== 'string')
155
+ renameInExpression(source, p.expr, p.start, names, shadow, false, edits);
156
+ }
157
+ else if (a.kind !== 'static')
158
+ renameInExpression(source, a.expr, source.indexOf('=', a.start + a.name.length) + 1, names, shadow, a.kind === 'event', edits);
159
+ }
160
+ renameInTemplate(source, n.children, names, shadow, edits);
161
+ }
162
+ else if (n.type === 'if') {
163
+ for (const b of n.branches) {
164
+ if (b.cond)
165
+ renameInExpression(source, b.cond, b.condStart, names, shadow, false, edits);
166
+ renameInTemplate(source, b.children, names, shadow, edits);
167
+ }
168
+ }
169
+ else if (n.type === 'for') {
170
+ renameInExpression(source, n.list, n.listStart, names, shadow, false, edits);
171
+ const inner = new Set([...shadow, n.item, ...n.aliases.map((a) => a.name)]);
172
+ if (n.track)
173
+ renameInExpression(source, n.track, n.trackStart, names, inner, false, edits);
174
+ renameInTemplate(source, n.children, names, inner, edits);
175
+ if (n.empty)
176
+ renameInTemplate(source, n.empty, names, shadow, edits);
177
+ }
178
+ else if (n.type === 'await') {
179
+ renameInExpression(source, n.expr, n.exprStart, names, shadow, false, edits);
180
+ renameInTemplate(source, n.pending, names, shadow, edits);
181
+ if (n.then)
182
+ renameInTemplate(source, n.then.children, names, new Set([...shadow, n.then.name]), edits);
183
+ if (n.catch)
184
+ renameInTemplate(source, n.catch.children, names, new Set([...shadow, n.catch.name]), edits);
185
+ }
186
+ else if (n.type === 'fill')
187
+ renameInTemplate(source, n.children, names, new Set([...shadow, ...(n.params ? fillNames(n.params) : [])]), edits);
188
+ }
189
+ }
190
+ const indentDoc = (doc, indent) => doc.split('\n').map((l, i) => (i === 0 ? l.trim() : ` ${l.trim()}`)).join(`\n${indent}`);
191
+ const lineEnd = (source, at) => { const n = source.indexOf('\n', at); return n === -1 ? source.length : n + 1; };
192
+ export function migrate(source, file) {
193
+ const parsed = parse(source, file);
194
+ const notes = [];
195
+ const inputs = parsed.inputs.filter((i) => !i.model);
196
+ const models = parsed.inputs.filter((i) => i.model);
197
+ if (!inputs.length && !models.length && !parsed.events.length && !parsed.types.length && !parsed.typeImports.length)
198
+ return { code: source, notes };
199
+ if (parsed.contexts.length)
200
+ notes.push(`${file}: @context ${parsed.contexts.map((c) => c.name).join(', ')} kept (context() reads through a typed key; see the context guide)`);
201
+ if (parsed.props || parsed.script?.factories?.length)
202
+ return { code: source, notes: [...notes, `${file}: already uses props()/model()/events(); left as it is`] };
203
+ const edits = [];
204
+ let island = true;
205
+ try {
206
+ island = compile(source, { file, target: 'client' }).code.trim() !== 'export {}';
207
+ }
208
+ catch { }
209
+ const commentBefore = (at) => {
210
+ const before = source.slice(0, at).replace(/\s+$/, '');
211
+ if (!before.endsWith('--}}'))
212
+ return undefined;
213
+ const start = before.lastIndexOf('{{--');
214
+ if (start === -1 || !/\S/.test(source.slice(0, start)))
215
+ return undefined;
216
+ const lines = before.slice(start + 4, -4).trim().split('\n').map((l) => l.trim()).filter(Boolean);
217
+ return { start, doc: lines.length === 1 ? `/** ${lines[0]} */` : `/**\n${lines.map((l) => ` * ${l}`).join('\n')}\n */` };
218
+ };
219
+ for (const d of [...parsed.inputs, ...parsed.types])
220
+ if (!d.doc) {
221
+ const c = commentBefore(d.start);
222
+ if (c)
223
+ Object.assign(d, { doc: c.doc, commentStart: c.start });
224
+ }
225
+ const withDoc = (start, doc) => {
226
+ const from = parsed.inputs.concat(parsed.types).find((d) => d.start === start)?.commentStart;
227
+ if (from !== undefined)
228
+ return from;
229
+ const at = doc ? source.lastIndexOf(doc, start) : -1;
230
+ return at === -1 ? start : at;
231
+ };
232
+ const drop = (from, last) => edits.push({ start: from, end: lineEnd(source, last), text: '' });
233
+ for (const i of parsed.inputs)
234
+ drop(withDoc(i.start, i.doc), i.defaultStart !== undefined ? i.defaultStart + i.default.length - 1 : i.typeStart + i.type.length - 1);
235
+ for (const t of parsed.types)
236
+ drop(withDoc(t.start, t.doc), t.typeStart + t.type.length - 1);
237
+ for (const t of parsed.typeImports)
238
+ drop(t.start, t.start);
239
+ for (const e of parsed.events)
240
+ drop(e.start, e.start);
241
+ const dataImports = island ? [] : parsed.dataImports;
242
+ for (const d of dataImports)
243
+ drop(d.start, d.start);
244
+ if (island)
245
+ for (const d of parsed.dataImports)
246
+ notes.push(`${file}: @import ${d.clause} from '${d.from}' kept (an island: as a script import it would ship to the browser)`);
247
+ const decl = [];
248
+ for (const d of dataImports)
249
+ decl.push(`import ${d.clause} from '${d.from}'`);
250
+ for (const t of parsed.typeImports)
251
+ decl.push(`import type ${t.clause} from '${t.from}'`);
252
+ for (const t of parsed.types)
253
+ decl.push(...(t.doc ? [indentDoc(t.doc, ' ')] : []), t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ${t.type}` : `type ${t.name}${t.params ?? ''} = ${t.type}`);
254
+ if (inputs.length) {
255
+ const members = inputs.map((i) => `${i.doc ? ` ${indentDoc(i.doc, ' ')}\n` : ''} ${i.name}${i.default !== undefined ? '?' : ''}: ${i.type}`);
256
+ const defaults = inputs.filter((i) => i.default !== undefined);
257
+ decl.push(`const props = props<{\n${members.join('\n')}\n }>(${defaults.length ? `() => ({ ${defaults.map((i) => `${i.name}: ${i.default}`).join(', ')} })` : ''})`);
258
+ }
259
+ for (const m of models)
260
+ decl.push(...(m.doc ? [indentDoc(m.doc, ' ')] : []), `let ${m.name} = model<${m.type}>(${m.default !== undefined ? `() => ${/^\{/.test(m.default) ? `(${m.default})` : m.default}` : ''})`);
261
+ if (parsed.events.length)
262
+ decl.push(`const emit = events<{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join('; ')} }>()`);
263
+ const block = decl.map((l) => ` ${l}`).join('\n');
264
+ const names = new Set(inputs.map((i) => i.name));
265
+ if (names.size) {
266
+ renameInTemplate(source, parsed.nodes, names, new Set(), edits);
267
+ for (const s of [parsed.script])
268
+ if (s)
269
+ renameReads(acornParse(s.code, OPTS), names, new Set(), s.start, edits);
270
+ if (parsed.serverScript)
271
+ notes.push(`${file}: its <script server> reads inputs by name; left as it is (props.name there too, by hand)`);
272
+ }
273
+ if (parsed.script) {
274
+ const s = parsed.script;
275
+ const tag = source.lastIndexOf('<script', s.start);
276
+ if (!/\blang=/.test(source.slice(tag, s.start))) {
277
+ edits.push({ start: tag + '<script'.length, end: tag + '<script'.length, text: ' lang="ts"' });
278
+ notes.push(`${file}: its <script> is now TypeScript: give its untyped function parameters types (clarusjs check lists them)`);
279
+ }
280
+ const imports = acornParse(s.code, OPTS).body.filter((x) => x.type === 'ImportDeclaration');
281
+ const at = imports.length ? s.start + imports[imports.length - 1].end : s.start;
282
+ edits.push({ start: at, end: at, text: `${imports.length ? '\n' : '\n'}${block}${imports.length ? '' : '\n'}` });
283
+ }
284
+ else {
285
+ const first = Math.min(...[...parsed.inputs.map((i) => withDoc(i.start, i.doc)), ...parsed.types.map((t) => withDoc(t.start, t.doc)), ...parsed.typeImports.map((t) => t.start), ...parsed.events.map((e) => e.start), ...dataImports.map((d) => d.start)]);
286
+ edits.push({ start: first, end: first, text: `<script lang="ts">\n${block}\n</script>\n\n` });
287
+ }
288
+ edits.sort((a, b) => b.start - a.start || (a.end === a.start ? 1 : 0) - (b.end === b.start ? 1 : 0));
289
+ let code = source;
290
+ for (const e of edits)
291
+ code = code.slice(0, e.start) + e.text + code.slice(e.end);
292
+ return { code: code.replace(/\n{3,}/g, '\n\n'), notes };
293
+ }
@@ -74,7 +74,7 @@ export function emitClient(ir, hot) {
74
74
  out += ` __cl_declare(__cl_root, ${JSON.stringify(ir.sendNames)})\n`;
75
75
  if (ir.sends)
76
76
  out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
77
- out += contextLines(ir, 'undefined');
77
+ out += contextLines(ir, '__cl_props.__cl_cx');
78
78
  if (ir.provides)
79
79
  out += ` __cl_provideOn(__cl_root, __cl_cx)\n`;
80
80
  const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
@@ -85,6 +85,8 @@ export function emitClient(ir, hot) {
85
85
  : ` const ${i.name} = state(${value(i, '__cl_props')})\n`;
86
86
  }
87
87
  out += inputsLine({ ...ir, inputs: ir.inputs.filter((i) => !inputs.includes(i)) });
88
+ if (ir.props)
89
+ out += ` const ${ir.props.name} = { ${ir.props.keys.map((k) => `get ${k}() { return ${rewriteClientExpr(k, ir.signals)} }`).join(', ')} }\n`;
88
90
  if (ir.script)
89
91
  out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true, forms: formName(ir.scriptImports) }));
90
92
  const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
@@ -1,6 +1,6 @@
1
1
  import { asWritten, htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
- import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
3
+ import { contextLines, contextName, indentScript, inputsLine, renderName } from './shared.js';
4
4
  export function emitServer(ir, clientUrl, renderImports = false, loader) {
5
5
  const all = walk(ir.nodes);
6
6
  const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null, top: true });
@@ -34,7 +34,10 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
34
34
  out += `${line}\n`;
35
35
  for (const line of ir.server?.imports ?? [])
36
36
  out += `${line}\n`;
37
- const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
37
+ const notPublic = (c) => `(() => { throw new Error("[clarusjs] <${ir.name}> is an island and reads context \\"" + ${contextName(c)} + "\\", which isn't public: its value would be written into the page. The key it's read with and the key it's provided with must both be contextKey(name, { public: true })") })()`;
38
+ const sendable = (c) => `${c.key}.public === true && (!__cl_cx || !{}.hasOwnProperty.call(__cl_cx, ${contextName(c)}) || __cl_cx[Symbol.for("clarusjs.publicContext")]?.has(${contextName(c)}) === true)`;
39
+ const cx = ir.contexts.length ? [`__cl_cx: { ${ir.contexts.map((c) => (c.key ? `[${contextName(c)}]: ${sendable(c)} ? ${c.name} : ${notPublic(c)}` : `[${contextName(c)}]: ${c.name}`)).join(', ')} }`] : [];
40
+ const props = `{ ${[...ir.inputs.map((i) => i.name), ...cx, '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
38
41
  out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
39
42
  out += unknownSlotCheck(ir);
40
43
  if (!ir.stateful)
@@ -42,6 +45,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
42
45
  if (loader)
43
46
  out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
44
47
  out += inputsLine(ir);
48
+ if (ir.props)
49
+ out += ` const ${ir.props.name} = { ${ir.props.keys.join(', ')} }\n`;
45
50
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
46
51
  if (html.includes('__cl_attrs'))
47
52
  out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))}${ir.extends ? `, ${JSON.stringify(ir.extends)}` : ''})\n`;