clarusjs 0.19.1 → 0.21.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.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/dist/check/generate.js +124 -25
  3. package/dist/cli/index.js +17 -0
  4. package/dist/cli/migrate-files.d.ts +5 -0
  5. package/dist/cli/migrate-files.js +22 -0
  6. package/dist/cli/migrate.d.ts +8 -0
  7. package/dist/cli/migrate.js +317 -0
  8. package/dist/compiler/emit-client.js +7 -4
  9. package/dist/compiler/emit-server.js +10 -3
  10. package/dist/compiler/factories.d.ts +38 -0
  11. package/dist/compiler/factories.js +273 -0
  12. package/dist/compiler/html-expr.d.ts +4 -0
  13. package/dist/compiler/html-expr.js +5 -1
  14. package/dist/compiler/index.js +8 -9
  15. package/dist/compiler/ir.d.ts +13 -0
  16. package/dist/compiler/ir.js +41 -12
  17. package/dist/compiler/jsdoc.d.ts +15 -0
  18. package/dist/compiler/jsdoc.js +81 -0
  19. package/dist/compiler/lint.js +9 -4
  20. package/dist/compiler/parse.d.ts +35 -9
  21. package/dist/compiler/parse.js +77 -8
  22. package/dist/compiler/script.d.ts +15 -5
  23. package/dist/compiler/script.js +112 -18
  24. package/dist/compiler/shared.d.ts +5 -0
  25. package/dist/compiler/shared.js +5 -3
  26. package/dist/compiler/strip-types.d.ts +20 -0
  27. package/dist/compiler/strip-types.js +148 -0
  28. package/dist/forms/index.js +26 -5
  29. package/dist/runtime/context.d.ts +39 -0
  30. package/dist/runtime/context.js +4 -0
  31. package/dist/runtime/fragments.js +6 -2
  32. package/dist/runtime/index.d.ts +1 -0
  33. package/dist/runtime/index.js +1 -0
  34. package/dist/runtime/navigate.js +2 -1
  35. package/dist/runtime/signals.d.ts +11 -6
  36. package/dist/runtime/signals.js +12 -3
  37. package/dist/vite/base-clash.d.ts +9 -0
  38. package/dist/vite/base-clash.js +54 -0
  39. package/dist/vite/build-app.d.ts +5 -0
  40. package/dist/vite/build-app.js +185 -0
  41. package/dist/vite/dev-server.d.ts +5 -0
  42. package/dist/vite/dev-server.js +67 -0
  43. package/dist/vite/graph.d.ts +45 -0
  44. package/dist/vite/graph.js +125 -0
  45. package/dist/vite/hmr.d.ts +19 -0
  46. package/dist/vite/hmr.js +53 -0
  47. package/dist/vite/links.d.ts +2 -0
  48. package/dist/vite/links.js +2 -0
  49. package/dist/vite/options.d.ts +147 -0
  50. package/dist/vite/options.js +1 -0
  51. package/dist/vite/output.d.ts +25 -0
  52. package/dist/vite/output.js +49 -0
  53. package/dist/vite/plugin.d.ts +4 -150
  54. package/dist/vite/plugin.js +68 -624
  55. package/dist/vite/preview.d.ts +3 -0
  56. package/dist/vite/preview.js +100 -0
  57. package/dist/vite/server-entry.d.ts +18 -0
  58. package/dist/vite/server-entry.js +83 -0
  59. package/dist/vite/shared.d.ts +34 -0
  60. package/dist/vite/shared.js +47 -0
  61. package/dist/vite/styles.d.ts +16 -0
  62. package/dist/vite/styles.js +56 -0
  63. package/package.json +6 -4
@@ -116,6 +116,27 @@ export type TemplateNode = {
116
116
  start: number;
117
117
  transition?: Transition;
118
118
  };
119
+ /**
120
+ * A component's script. `code` is JavaScript; with `lang="ts"` it's the TypeScript with its types turned to spaces
121
+ * (every position the same), `ts` is the TypeScript as written and `typeImports` its type-only imports (type checking
122
+ * reads those).
123
+ */
124
+ export type Script = {
125
+ code: string;
126
+ start: number;
127
+ ts?: string;
128
+ typeImports?: {
129
+ text: string;
130
+ start: number;
131
+ }[];
132
+ typeDecls?: {
133
+ text: string;
134
+ start: number;
135
+ }[]; /** props()/model()/events() statements: what they declare is in inputs and events. */
136
+ factories?: [number, number][]; /** The names those statements' arguments use (for linters: they're spaces in `code`). */
137
+ factoryRefs?: string[]; /** Where `export` starts on a type that stays in the script (type checking drops the keyword). */
138
+ stayingExports?: number[];
139
+ };
119
140
  /**
120
141
  * An `@input` (or `@model`) declaration: its name, type text, default, and offsets.
121
142
  * @see https://clarusjs.com/reference/compiler#parse
@@ -128,7 +149,11 @@ export type InputDecl = {
128
149
  nameStart: number;
129
150
  typeStart: number;
130
151
  defaultStart?: number;
131
- model?: true;
152
+ model?: true; /** The `/** … *\/` right before it, as written: what editors show for it. */
153
+ doc?: string; /** A context read with a typed key: the key's expression (context(tabsKey)). */
154
+ key?: string; /** props<{ a?: T }>() without a default: optional all the same. */
155
+ optional?: true; /** A factory default as written, TypeScript (`default` is it stripped, for the compiler). */
156
+ defaultTs?: string;
132
157
  };
133
158
  export type TypeImport = {
134
159
  clause: string;
@@ -169,7 +194,8 @@ export type TypeDecl = {
169
194
  type: string;
170
195
  start: number;
171
196
  nameStart: number;
172
- typeStart: number;
197
+ typeStart: number; /** The `/** … *\/` right before it, as written. */
198
+ doc?: string;
173
199
  };
174
200
  /**
175
201
  * A `.tscl` file's syntax tree, as `parse()` gives it: inputs, imports, the script, styles and template nodes.
@@ -185,16 +211,16 @@ export type ParsedFile = {
185
211
  typeImports: TypeImport[];
186
212
  types: TypeDecl[];
187
213
  dataImports: DataImport[];
188
- script?: {
189
- code: string;
190
- start: number;
191
- };
214
+ script?: Script;
192
215
  /** <script server> (#430): runs at render on the server only. `tag` = offset of `<script`. */
193
- serverScript?: {
194
- code: string;
195
- start: number;
216
+ serverScript?: Script & {
196
217
  tag: number;
197
218
  };
219
+ /** props<T>() in the script: the variable it's read through (props.name), and the props it holds. */
220
+ props?: {
221
+ name: string;
222
+ keys: string[];
223
+ };
198
224
  styles: {
199
225
  css: string;
200
226
  mode: 'scoped' | 'global' | 'plain';
@@ -1,12 +1,14 @@
1
1
  import { ClarusError } from './errors.js';
2
+ import { stripTypes, StripError } from './strip-types.js';
3
+ import { factories } from './factories.js';
2
4
  export const awaitLists = (n) => [n.pending, ...(n.then ? [n.then.children] : []), ...(n.catch ? [n.catch.children] : [])];
3
5
  export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
4
6
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
5
7
  const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
6
- const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
8
+ const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
7
9
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
8
10
  const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
9
- const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim()];
11
+ const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim().replace(/^\*\s+as\s+/, '')];
10
12
  export function rootNodes(nodes) {
11
13
  return nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && ['cl-head', 'script', 'style'].includes(n.tag)));
12
14
  }
@@ -20,6 +22,65 @@ export function parse(source, file) {
20
22
  let i = 0;
21
23
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
22
24
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
25
+ let doc;
26
+ const docComment = (at) => {
27
+ if (!source.startsWith('/**', at) || source.startsWith('/**/', at) || !atLineStart(at))
28
+ return undefined;
29
+ const close = source.indexOf('*/', at + 3);
30
+ if (close === -1)
31
+ return undefined;
32
+ const next = /^\s*@(input|model|context|type|interface|import)\s/.exec(source.slice(close + 2));
33
+ return next && /\n/.test(next[0]) ? { text: source.slice(at, close + 2), end: close + 2 } : undefined;
34
+ };
35
+ const declare = (made, start) => {
36
+ for (const i of made.inputs)
37
+ out.inputs.push({ ...i, start: start + i.start, nameStart: start + i.nameStart, typeStart: start + i.typeStart, ...(i.defaultStart !== undefined ? { defaultStart: start + i.defaultStart } : {}) });
38
+ for (const c of made.contexts)
39
+ out.contexts.push({ ...c, start: start + c.start, nameStart: start + c.nameStart, typeStart: start + c.typeStart, ...(c.defaultStart !== undefined ? { defaultStart: start + c.defaultStart } : {}) });
40
+ for (const e of made.events)
41
+ out.events.push({ ...e, start: start + e.start, nameStart: start + e.nameStart, typeStart: start + e.typeStart });
42
+ if (made.props)
43
+ out.props = made.props;
44
+ };
45
+ const blanked = (code, made) => {
46
+ for (const [from, to] of made.blank)
47
+ code = code.slice(0, from) + code.slice(from, to).replace(/[^\n]/g, ' ') + code.slice(to);
48
+ return code;
49
+ };
50
+ const script = (code, start, attrs) => {
51
+ const lang = attrs.find((a) => a.name === 'lang');
52
+ if (!lang) {
53
+ if (!/\b(props|model|events|context)\b/.test(code))
54
+ return { code, start };
55
+ try {
56
+ const made = factories(code, code, { js: true });
57
+ if (!made.blank.length)
58
+ return { code, start };
59
+ declare(made, start);
60
+ return { code: blanked(code, made), start, factories: made.blank, factoryRefs: made.refs };
61
+ }
62
+ catch (e) {
63
+ if (e instanceof StripError)
64
+ fail(e.message, start + e.pos);
65
+ return { code, start };
66
+ }
67
+ }
68
+ if (lang.kind !== 'static' || !['ts', 'typescript'].includes(String(lang.value)))
69
+ fail('<script lang> takes "ts"', lang.start);
70
+ try {
71
+ const js = stripTypes(code);
72
+ const made = factories(code, js.code);
73
+ const jsCode = blanked(js.code, made);
74
+ declare(made, start);
75
+ return { code: jsCode, start, ts: code, typeImports: js.typeImports, typeDecls: js.typeDecls, ...(js.stayingExports.length ? { stayingExports: js.stayingExports } : {}), ...(made.blank.length ? { factories: made.blank, factoryRefs: made.refs } : {}) };
76
+ }
77
+ catch (e) {
78
+ if (e instanceof StripError)
79
+ fail(e.message, start + e.pos);
80
+ throw e;
81
+ }
82
+ };
83
+ const takeDoc = () => { const d = doc; doc = undefined; return d ? { doc: d } : {}; };
23
84
  function directive() {
24
85
  const end = source.indexOf('\n', i) === -1 ? source.length : source.indexOf('\n', i);
25
86
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
@@ -147,7 +208,7 @@ export function parse(source, file) {
147
208
  fallback = { default: value, defaultStart: at };
148
209
  }
149
210
  ;
150
- (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
211
+ (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}), ...takeDoc() });
151
212
  i = end;
152
213
  }
153
214
  function typeDecl(lineStart) {
@@ -191,7 +252,7 @@ export function parse(source, file) {
191
252
  fail(`@type ${name} is declared twice`, i);
192
253
  if (out.typeImports.some((t) => typeNames(t.clause).includes(name)))
193
254
  fail(`@type ${name} is already imported with @import type`, i);
194
- out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos });
255
+ out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos, ...takeDoc() });
195
256
  i = end;
196
257
  }
197
258
  function attrs() {
@@ -663,9 +724,17 @@ export function parse(source, file) {
663
724
  i++;
664
725
  return nodes;
665
726
  }
727
+ else if (!parent && source[i] === '/' && docComment(i)) {
728
+ flush();
729
+ const d = docComment(i);
730
+ doc = d.text;
731
+ i = d.end;
732
+ textStart = i;
733
+ }
666
734
  else if (!parent && source[i] === '@' && atLineStart(i)) {
667
735
  flush();
668
736
  directive();
737
+ doc = undefined;
669
738
  textStart = i;
670
739
  }
671
740
  else if (source.startsWith('{{', i)) {
@@ -731,13 +800,13 @@ export function parse(source, file) {
731
800
  fail('<script server> must be at the top level (it runs once per render, before the template)', start);
732
801
  if (out.serverScript)
733
802
  fail('only one <script server> block is allowed', start);
734
- const other = list.find((a) => a.name !== 'server');
803
+ const other = list.find((a) => a.name !== 'server' && a.name !== 'lang');
735
804
  if (other)
736
- fail('<script server> takes no other attributes', other.start);
805
+ fail('<script server> takes no other attributes than lang="ts"', other.start);
737
806
  const end = source.indexOf('</script>', i);
738
807
  if (end === -1)
739
808
  fail('unclosed <script server>', start);
740
- out.serverScript = { code: source.slice(i, end), start: i, tag: start };
809
+ out.serverScript = { ...script(source.slice(i, end), i, list), tag: start };
741
810
  i = end + '</script>'.length;
742
811
  }
743
812
  else if (tag === 'script') {
@@ -748,7 +817,7 @@ export function parse(source, file) {
748
817
  const end = source.indexOf('</script>', i);
749
818
  if (end === -1)
750
819
  fail('unclosed <script>', start);
751
- out.script = { code: source.slice(i, end), start: i };
820
+ out.script = script(source.slice(i, end), i, list);
752
821
  i = end + '</script>'.length;
753
822
  }
754
823
  else if (tag === 'style' && !parent) {
@@ -9,6 +9,11 @@ export declare function checkHandler(code: string, file: string, source: string,
9
9
  export declare function templateRanges(code: string): [number, number][];
10
10
  /** Parenthesize expressions whose meaning changes when inlined as an argument or arrow body (`a, b`, `{ … }`). */
11
11
  export declare function wrapExpr(expr: string): string;
12
+ /**
13
+ * Whether a script calls a runtime function it didn't import or declare at its top level: effect(), which (like
14
+ * state() and derived()) a script uses without importing. `imports` are the script's import statements.
15
+ */
16
+ export declare function usesRuntime(code: string, imports: readonly string[], name: string): boolean;
12
17
  /** Names declared at the top level of <script>: variables, functions, classes. */
13
18
  export declare function scriptNames(code: string): Set<string>;
14
19
  /**
@@ -34,15 +39,16 @@ export declare function serverScriptParts(code: string, file: string, source: st
34
39
  awaits: boolean;
35
40
  };
36
41
  /**
37
- * Where type annotations go for type checking: `: any` after the untyped parameters of the script's own functions
38
- * (declarations, `const f = (x) => …`, class methods) and of callbacks passed straight to them (`record((p) => …)`).
39
- * A script is JavaScript, so nothing else types those, and a strict project would report each one. Other callbacks
40
- * keep their contextual type; a parameter with a default takes its type.
42
+ * Type annotations for type checking, which reads the script (JavaScript) as TypeScript: JSDoc `@param`, `@returns`,
43
+ * `@type` and `@typedef` as annotations; otherwise `: any` on the untyped parameters of the script's own functions and
44
+ * of callbacks passed straight to them (a strict project would report each). Other callbacks keep their context.
41
45
  */
42
- export declare function untypedParams(code: string): {
46
+ export declare function scriptAnnotations(code: string): {
43
47
  at: number;
44
48
  text: string;
45
49
  }[];
50
+ /** A script's JSDoc `@import { A } from '…'` tags, as `import type` lines for the top of the checked file. */
51
+ export declare function scriptTypeImports(code: string): string[];
46
52
  export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
47
53
  /** Do these import statements bring in form from clarusjs/forms (so `form(x)` is the engine's, not a function of its own)? */
48
54
  export declare function formName(imports: string[]): string | undefined;
@@ -66,6 +72,10 @@ export declare function providesIn(split: {
66
72
  }[];
67
73
  body: string;
68
74
  }, file: string, source: string, offset: number): boolean;
75
+ /** Whether `code` has any statement (comments and blank space don't count). */
76
+ export declare const hasStatements: (code: string) => boolean;
77
+ /** A <script server>'s provide(key, value) calls as provide(key, () => (value)), as the script's are (read when a child renders). */
78
+ export declare function provideGetters(code: string): string;
69
79
  export declare function rewriteServer(code: string): string;
70
80
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
71
81
  /**
@@ -1,6 +1,7 @@
1
1
  import { tokenizer, parse as acornParse, parseExpressionAt } from 'acorn';
2
2
  import { FOR_IMPLICIT } from './parse.js';
3
3
  import { ClarusError } from './errors.js';
4
+ import { jsdocImports, tags, typedefs } from './jsdoc.js';
4
5
  const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
5
6
  function isNode(v) {
6
7
  return !!v && typeof v.type === 'string' && typeof v.start === 'number';
@@ -52,7 +53,8 @@ function print(node, code, hook, parent = null, key = '') {
52
53
  return out + code.slice(pos, node.end);
53
54
  }
54
55
  const TS = 'TypeScript syntax in a <script> (scripts are JavaScript): ';
55
- const TS_WHERE = '. Types come from @input, inference, and the .ts modules a script imports';
56
+ const EXPORT_WHY = "its names are for this component's template, and it runs once per use. Put a value other files need in a .ts module and import it here; a type can be exported (export interface, export type), or written as a JSDoc @typedef";
57
+ const TS_WHERE = '. For TypeScript, write <script lang="ts">; in JavaScript, types come from JSDoc, @input and the .ts modules a script imports';
56
58
  function typescriptAt(code, pos) {
57
59
  const before = code.slice(0, pos).trimEnd();
58
60
  const at = code.slice(pos);
@@ -238,6 +240,17 @@ export function wrapExpr(expr) {
238
240
  const t = parseExpr(expr).type;
239
241
  return t === 'SequenceExpression' || t === 'ObjectExpression' ? `(${expr})` : expr;
240
242
  }
243
+ export function usesRuntime(code, imports, name) {
244
+ if (scriptNames(code).has(name) || imports.some((line) => scriptNames(line).has(name)))
245
+ return false;
246
+ let found = false;
247
+ print(parseScript(code), code, (node, parent, key) => {
248
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === name && !isBinding(parent, key))
249
+ found = true;
250
+ return undefined;
251
+ });
252
+ return found;
253
+ }
241
254
  export function scriptNames(code) {
242
255
  const names = new Set();
243
256
  for (const stmt of parseScript(code).body) {
@@ -282,7 +295,7 @@ export function serverScriptParts(code, file, source, offset) {
282
295
  let body = code;
283
296
  for (const stmt of ast.body) {
284
297
  if (stmt.type.startsWith('Export'))
285
- throw new ClarusError('a <script server> cannot export anything: its names are for the template', file, source, offset + stmt.start);
298
+ throw new ClarusError(`a <script server> can't export a value: ${EXPORT_WHY}`, file, source, offset + stmt.start);
286
299
  if (stmt.type !== 'ImportDeclaration')
287
300
  continue;
288
301
  imports.push(code.slice(stmt.start, stmt.end));
@@ -290,41 +303,115 @@ export function serverScriptParts(code, file, source, offset) {
290
303
  }
291
304
  return { imports, body, awaits: !!topLevelAwait(ast) };
292
305
  }
293
- export function untypedParams(code) {
306
+ export function scriptAnnotations(code) {
294
307
  const ast = parseScript(code);
308
+ const comments = [];
309
+ acornParse(code, { ...OPTS, onComment: (block, text, start, end) => { if (block && text.startsWith('*'))
310
+ comments.push({ text: `/*${text}*/`, start, end }); } });
311
+ const docBefore = (start) => {
312
+ let found;
313
+ for (const c of comments)
314
+ if (c.end <= start)
315
+ found = /\S/.test(code.slice(c.end, start)) ? undefined : c.text;
316
+ return found;
317
+ };
295
318
  const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
296
319
  const own = new Map();
320
+ const typedParam = new Map();
321
+ const typedBy = (doc, params) => {
322
+ const named = doc ? tags(doc).filter((t) => t.tag === 'param' && t.type && t.name && !t.name.includes('.')) : [];
323
+ return (i) => { const p = params[i]; const id = p?.type === 'AssignmentPattern' ? p.left : p; return id?.type === 'Identifier' ? named.some((t) => t.name === id.name) : !!named[i]; };
324
+ };
297
325
  for (const stmt of ast.body) {
298
- if (stmt.type === 'FunctionDeclaration' && stmt.id)
326
+ if (stmt.type === 'FunctionDeclaration' && stmt.id) {
299
327
  own.set(stmt.id.name, stmt.params);
328
+ typedParam.set(stmt.id.name, typedBy(docBefore(stmt.start), stmt.params));
329
+ }
300
330
  if (stmt.type === 'VariableDeclaration')
301
331
  for (const d of stmt.declarations)
302
- if (d.id.type === 'Identifier' && isFn(d.init))
332
+ if (d.id.type === 'Identifier' && isFn(d.init)) {
303
333
  own.set(d.id.name, d.init.params);
334
+ typedParam.set(d.id.name, typedBy(docBefore(stmt.start), d.init.params));
335
+ }
304
336
  }
337
+ const edits = [];
305
338
  const targets = new Set();
339
+ const docs = new Map();
340
+ const typed = new Set();
306
341
  print(ast, code, (node, parent, key) => {
342
+ if (node.type === 'VariableDeclaration') {
343
+ const doc = docBefore(node.start);
344
+ const type = doc && tags(doc).find((t) => t.tag === 'type')?.type;
345
+ for (const d of node.declarations) {
346
+ if (type && d.id.type === 'Identifier' && node.declarations.length === 1) {
347
+ edits.push({ at: d.id.end, text: `: ${type}` });
348
+ if (isFn(d.init))
349
+ typed.add(d.init);
350
+ }
351
+ else if (doc && isFn(d.init))
352
+ docs.set(d.init, doc);
353
+ }
354
+ }
355
+ if (node.type === 'FunctionDeclaration' || (isFn(node) && parent?.type !== 'VariableDeclarator')) {
356
+ const doc = docBefore(parent?.type === 'MethodDefinition' ? parent.start : node.start);
357
+ if (doc)
358
+ docs.set(node, doc);
359
+ }
307
360
  if (node.type === 'FunctionDeclaration' || (isFn(node) && ((parent?.type === 'VariableDeclarator' && key === 'init') || parent?.type === 'MethodDefinition')))
308
361
  targets.add(node);
309
362
  const params = node.type === 'CallExpression' && node.callee.type === 'Identifier' ? own.get(node.callee.name) : undefined;
310
363
  if (params)
311
- node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern')
364
+ node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern' && !typedParam.get(node.callee.name)?.(i))
312
365
  targets.add(arg); });
313
366
  return undefined;
314
367
  });
315
- const edits = [];
316
- for (const fn of targets) {
317
- for (const p of fn.params) {
318
- if (p.type === 'AssignmentPattern')
319
- continue;
320
- const bare = fn.type === 'ArrowFunctionExpression' && !code.slice(fn.start, p.start).includes('(');
321
- if (bare)
368
+ for (const fn of new Set([...targets, ...docs.keys()])) {
369
+ if (typed.has(fn))
370
+ continue;
371
+ const all = docs.has(fn) ? tags(docs.get(fn)) : [];
372
+ const params = all.filter((t) => t.tag === 'param' && t.name && !t.name.includes('.'));
373
+ const bareArrow = fn.type === 'ArrowFunctionExpression' && fn.params.length === 1 && !code.slice(fn.start, fn.params[0].start).includes('(');
374
+ const returns = all.find((t) => (t.tag === 'returns' || t.tag === 'return') && t.type)?.type;
375
+ let annotated = false;
376
+ fn.params.forEach((p, i) => {
377
+ const at = p.type === 'AssignmentPattern' ? p.left : p;
378
+ const tag = at.type === 'Identifier' ? params.find((t) => t.name === at.name) : at.type === 'RestElement' && at.argument.type === 'Identifier' ? params.find((t) => t.name === at.argument.name) : params[i];
379
+ let type = tag?.type;
380
+ if (type && at.type === 'RestElement')
381
+ type = type.startsWith('...') ? `${type.slice(3)}[]` : type;
382
+ if (!type) {
383
+ if (!targets.has(fn) || p.type === 'AssignmentPattern')
384
+ return;
385
+ type = p.type === 'RestElement' ? 'any[]' : 'any';
386
+ }
387
+ if (bareArrow)
322
388
  edits.push({ at: p.start, text: '(' });
323
- edits.push({ at: p.end, text: (p.type === 'RestElement' ? ': any[]' : ': any') + (bare ? ')' : '') });
389
+ const optional = tag?.optional && at === p && p.type === 'Identifier' ? '?' : '';
390
+ edits.push({ at: at.end, text: `${optional}: ${type}${bareArrow ? `)${returns ? `: ${returns}` : ''}` : ''}` });
391
+ if (bareArrow)
392
+ annotated = true;
393
+ });
394
+ if (returns && bareArrow && !annotated)
395
+ edits.push({ at: fn.params[0].start, text: '(' }, { at: fn.params[0].end, text: `): ${returns}` });
396
+ if (returns && !bareArrow) {
397
+ const close = code.indexOf(')', fn.params.length ? fn.params[fn.params.length - 1].end : fn.start);
398
+ if (close !== -1 && close < fn.body.start)
399
+ edits.push({ at: close + 1, text: `: ${returns}` });
324
400
  }
325
401
  }
402
+ for (const c of comments) {
403
+ const types = typedefs(c.text);
404
+ if (types)
405
+ edits.push({ at: c.end, text: ` ${types}` });
406
+ }
326
407
  return edits.sort((a, b) => a.at - b.at);
327
408
  }
409
+ export function scriptTypeImports(code) {
410
+ const out = [];
411
+ acornParse(code, { ...OPTS, onComment: (block, text) => { if (block && text.startsWith('*'))
412
+ out.push(...jsdocImports(text)); } });
413
+ return out;
414
+ }
328
415
  const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
329
416
  export function analyzeScript(code, file, source, offset) {
330
417
  const signals = new Map();
@@ -348,7 +435,7 @@ export function analyzeScript(code, file, source, offset) {
348
435
  throw new ClarusError("an island's <script> can't await at the top level (the browser attaches it without waiting): await data on the server in a <script server>, or in the browser inside a function, such as a resource()'s fetcher or an event handler", file, source, offset + tla.start);
349
436
  for (const stmt of ast.body) {
350
437
  if (stmt.type.startsWith('Export')) {
351
- throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
438
+ throw new ClarusError(`a <script> can't export a value: ${EXPORT_WHY}`, file, source, offset + stmt.start);
352
439
  }
353
440
  if (stmt.type !== 'VariableDeclaration')
354
441
  continue;
@@ -448,7 +535,7 @@ export function providesIn(split, file, source, offset) {
448
535
  }
449
536
  const code = split.body;
450
537
  let found = false;
451
- const usage = "provide is called with a string key and a value: provide('tabs', { value })";
538
+ const usage = "provide is called with a key and a value: provide('tabs', { value }), or provide(tabsKey, { value }) with a key from contextKey()";
452
539
  const hook = (node, parent, key) => {
453
540
  if (node.type === 'Identifier' && node.name === 'provide' && !(parent?.type === 'CallExpression' && key === 'callee') && (!isBinding(parent, key) || parent?.shorthand)) {
454
541
  throw new ClarusError(usage, file, source, offset + node.start);
@@ -459,10 +546,11 @@ export function providesIn(split, file, source, offset) {
459
546
  if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'provide') {
460
547
  found = true;
461
548
  const key = node.arguments[0];
462
- if (!key || key.type !== 'Literal' || typeof key.value !== 'string' || node.arguments.length !== 2) {
549
+ const typed = key && (key.type === 'Identifier' || key.type === 'MemberExpression');
550
+ if (!key || (!typed && (key.type !== 'Literal' || typeof key.value !== 'string')) || node.arguments.length !== 2) {
463
551
  throw new ClarusError(usage, file, source, offset + node.start);
464
552
  }
465
- if (!/^[A-Za-z_$][\w$]*$/.test(key.value))
553
+ if (!typed && !/^[A-Za-z_$][\w$]*$/.test(key.value))
466
554
  throw new ClarusError(`provide's key "${key.value}" isn't a name @context can read: use letters, digits, _ or $, like 'tabs'`, file, source, offset + node.start);
467
555
  }
468
556
  return undefined;
@@ -476,6 +564,12 @@ function provideCall(node, rec) {
476
564
  const [key, value] = node.arguments;
477
565
  return `provide(${rec(key)}, () => (${rec(value)}))`;
478
566
  }
567
+ export const hasStatements = (code) => parseScript(code).body.length > 0;
568
+ export function provideGetters(code) {
569
+ const ast = parseScript(code);
570
+ const hook = (node) => provideCall(node, (n) => print(n, code, hook));
571
+ return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
572
+ }
479
573
  export function rewriteServer(code) {
480
574
  const ast = parseScript(code);
481
575
  const hook = (node) => {
@@ -9,4 +9,9 @@ export declare const renderName: (name: string) => string;
9
9
  * script provides. provide(key, get) adds a getter, so a child reads the value current when it renders. Only when
10
10
  * the component calls components, places slots, reads context or provides.
11
11
  */
12
+ /** A context's name in the code: a string, or a typed key's name read at runtime. */
13
+ export declare const contextName: (c: {
14
+ name: string;
15
+ key?: string;
16
+ }) => string;
12
17
  export declare function contextLines(ir: ComponentIR, incoming: string): string;
@@ -20,16 +20,18 @@ export function indentScript(code) {
20
20
  return lines.map((l) => (l.literal ? l.text : ' ' + l.text.slice(indent))).join('\n') + '\n';
21
21
  }
22
22
  export const renderName = (name) => '__cl_render_' + name.replace(/-/g, '$');
23
+ export const contextName = (c) => (c.key ? `${c.key}.name` : JSON.stringify(c.name));
23
24
  export function contextLines(ir, incoming) {
24
25
  const all = walk(ir.nodes);
25
26
  if (!ir.provides && !ir.contexts.length && !all.some((n) => n.kind === 'component' || n.kind === 'slot'))
26
27
  return '';
27
28
  let out = ir.provides
28
- ? ` const __cl_cx = { ...${incoming} }\n const provide = (k, get) => { Object.defineProperty(__cl_cx, k, { get, enumerable: true, configurable: true }) }\n`
29
+ ? ` const __cl_cx = { ...${incoming}, [Symbol.for("clarusjs.publicContext")]: new Set(${incoming}?.[Symbol.for("clarusjs.publicContext")]) }\n const provide = (k, get) => { const n = typeof k === 'string' ? k : k.name; if (typeof n !== 'string') throw new Error("[clarusjs] provide: a context's name is a string"); Object.defineProperty(__cl_cx, n, { get, enumerable: true, configurable: true }); __cl_cx[Symbol.for("clarusjs.publicContext")][typeof k !== 'string' && k.public === true ? 'add' : 'delete'](n) }\n`
29
30
  : ` const __cl_cx = ${incoming}\n`;
30
31
  for (const c of ir.contexts) {
31
- const missing = `throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> reads context "${c.name}", which no component around it provides`)})`;
32
- out += ` const ${c.name} = __cl_cx && {}.hasOwnProperty.call(__cl_cx, ${JSON.stringify(c.name)}) ? __cl_cx.${c.name} : ${c.default !== undefined ? `(${c.default})` : `(() => { ${missing} })()`}\n`;
32
+ const k = contextName(c);
33
+ const missing = `throw new Error(${c.key ? `"[clarusjs] <${ir.name}> reads context \\"" + ${k} + "\\", which no component around it provides"` : JSON.stringify(`[clarusjs] <${ir.name}> reads context "${c.name}", which no component around it provides`)})`;
34
+ out += ` const ${c.name} = __cl_cx && {}.hasOwnProperty.call(__cl_cx, ${k}) ? ${c.key ? `__cl_cx[${k}]` : `__cl_cx.${c.name}`} : ${c.default !== undefined ? `(${c.default})` : `(() => { ${missing} })()`}\n`;
33
35
  }
34
36
  return out;
35
37
  }
@@ -0,0 +1,20 @@
1
+ export declare class StripError extends Error {
2
+ readonly pos: number;
3
+ constructor(message: string, pos: number);
4
+ }
5
+ /**
6
+ * `code` (TypeScript) as JavaScript of the same length, and its type-only imports as written (for type checking, which
7
+ * puts imports at the top of its file).
8
+ */
9
+ export declare function stripTypes(code: string): {
10
+ code: string;
11
+ typeImports: {
12
+ text: string;
13
+ start: number;
14
+ }[];
15
+ typeDecls: {
16
+ text: string;
17
+ start: number;
18
+ }[];
19
+ stayingExports: number[];
20
+ };