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.
@@ -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,45 @@ 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 script = (code, start, attrs) => {
36
+ const lang = attrs.find((a) => a.name === 'lang');
37
+ if (!lang)
38
+ return { code, start };
39
+ if (lang.kind !== 'static' || !['ts', 'typescript'].includes(String(lang.value)))
40
+ fail('<script lang> takes "ts"', lang.start);
41
+ try {
42
+ const js = stripTypes(code);
43
+ const made = factories(code, js.code);
44
+ let jsCode = js.code;
45
+ for (const [from, to] of made.blank)
46
+ jsCode = jsCode.slice(0, from) + jsCode.slice(from, to).replace(/[^\n]/g, ' ') + jsCode.slice(to);
47
+ for (const i of made.inputs)
48
+ out.inputs.push({ ...i, start: start + i.start, nameStart: start + i.nameStart, typeStart: start + i.typeStart, ...(i.defaultStart !== undefined ? { defaultStart: start + i.defaultStart } : {}) });
49
+ for (const c of made.contexts)
50
+ out.contexts.push({ ...c, start: start + c.start, nameStart: start + c.nameStart, typeStart: start + c.typeStart, ...(c.defaultStart !== undefined ? { defaultStart: start + c.defaultStart } : {}) });
51
+ for (const e of made.events)
52
+ out.events.push({ ...e, start: start + e.start, nameStart: start + e.nameStart, typeStart: start + e.typeStart });
53
+ if (made.props)
54
+ out.props = made.props;
55
+ 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 } : {}) };
56
+ }
57
+ catch (e) {
58
+ if (e instanceof StripError)
59
+ fail(e.message, start + e.pos);
60
+ throw e;
61
+ }
62
+ };
63
+ const takeDoc = () => { const d = doc; doc = undefined; return d ? { doc: d } : {}; };
23
64
  function directive() {
24
65
  const end = source.indexOf('\n', i) === -1 ? source.length : source.indexOf('\n', i);
25
66
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
@@ -147,7 +188,7 @@ export function parse(source, file) {
147
188
  fallback = { default: value, defaultStart: at };
148
189
  }
149
190
  ;
150
- (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
191
+ (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}), ...takeDoc() });
151
192
  i = end;
152
193
  }
153
194
  function typeDecl(lineStart) {
@@ -191,7 +232,7 @@ export function parse(source, file) {
191
232
  fail(`@type ${name} is declared twice`, i);
192
233
  if (out.typeImports.some((t) => typeNames(t.clause).includes(name)))
193
234
  fail(`@type ${name} is already imported with @import type`, i);
194
- out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos });
235
+ out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos, ...takeDoc() });
195
236
  i = end;
196
237
  }
197
238
  function attrs() {
@@ -663,9 +704,17 @@ export function parse(source, file) {
663
704
  i++;
664
705
  return nodes;
665
706
  }
707
+ else if (!parent && source[i] === '/' && docComment(i)) {
708
+ flush();
709
+ const d = docComment(i);
710
+ doc = d.text;
711
+ i = d.end;
712
+ textStart = i;
713
+ }
666
714
  else if (!parent && source[i] === '@' && atLineStart(i)) {
667
715
  flush();
668
716
  directive();
717
+ doc = undefined;
669
718
  textStart = i;
670
719
  }
671
720
  else if (source.startsWith('{{', i)) {
@@ -731,13 +780,13 @@ export function parse(source, file) {
731
780
  fail('<script server> must be at the top level (it runs once per render, before the template)', start);
732
781
  if (out.serverScript)
733
782
  fail('only one <script server> block is allowed', start);
734
- const other = list.find((a) => a.name !== 'server');
783
+ const other = list.find((a) => a.name !== 'server' && a.name !== 'lang');
735
784
  if (other)
736
- fail('<script server> takes no other attributes', other.start);
785
+ fail('<script server> takes no other attributes than lang="ts"', other.start);
737
786
  const end = source.indexOf('</script>', i);
738
787
  if (end === -1)
739
788
  fail('unclosed <script server>', start);
740
- out.serverScript = { code: source.slice(i, end), start: i, tag: start };
789
+ out.serverScript = { ...script(source.slice(i, end), i, list), tag: start };
741
790
  i = end + '</script>'.length;
742
791
  }
743
792
  else if (tag === 'script') {
@@ -748,7 +797,7 @@ export function parse(source, file) {
748
797
  const end = source.indexOf('</script>', i);
749
798
  if (end === -1)
750
799
  fail('unclosed <script>', start);
751
- out.script = { code: source.slice(i, end), start: i };
800
+ out.script = script(source.slice(i, end), i, list);
752
801
  i = end + '</script>'.length;
753
802
  }
754
803
  else if (tag === 'style' && !parent) {
@@ -34,15 +34,16 @@ export declare function serverScriptParts(code: string, file: string, source: st
34
34
  awaits: boolean;
35
35
  };
36
36
  /**
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.
37
+ * Type annotations for type checking, which reads the script (JavaScript) as TypeScript: JSDoc `@param`, `@returns`,
38
+ * `@type` and `@typedef` as annotations; otherwise `: any` on the untyped parameters of the script's own functions and
39
+ * of callbacks passed straight to them (a strict project would report each). Other callbacks keep their context.
41
40
  */
42
- export declare function untypedParams(code: string): {
41
+ export declare function scriptAnnotations(code: string): {
43
42
  at: number;
44
43
  text: string;
45
44
  }[];
45
+ /** A script's JSDoc `@import { A } from '…'` tags, as `import type` lines for the top of the checked file. */
46
+ export declare function scriptTypeImports(code: string): string[];
46
47
  export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
47
48
  /** Do these import statements bring in form from clarusjs/forms (so `form(x)` is the engine's, not a function of its own)? */
48
49
  export declare function formName(imports: string[]): string | undefined;
@@ -66,6 +67,10 @@ export declare function providesIn(split: {
66
67
  }[];
67
68
  body: string;
68
69
  }, file: string, source: string, offset: number): boolean;
70
+ /** Whether `code` has any statement (comments and blank space don't count). */
71
+ export declare const hasStatements: (code: string) => boolean;
72
+ /** A <script server>'s provide(key, value) calls as provide(key, () => (value)), as the script's are (read when a child renders). */
73
+ export declare function provideGetters(code: string): string;
69
74
  export declare function rewriteServer(code: string): string;
70
75
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
71
76
  /**
@@ -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,7 @@ 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 TS_WHERE = '. For TypeScript, write <script lang="ts">; in JavaScript, types come from JSDoc, @input and the .ts modules a script imports';
56
57
  function typescriptAt(code, pos) {
57
58
  const before = code.slice(0, pos).trimEnd();
58
59
  const at = code.slice(pos);
@@ -290,41 +291,115 @@ export function serverScriptParts(code, file, source, offset) {
290
291
  }
291
292
  return { imports, body, awaits: !!topLevelAwait(ast) };
292
293
  }
293
- export function untypedParams(code) {
294
+ export function scriptAnnotations(code) {
294
295
  const ast = parseScript(code);
296
+ const comments = [];
297
+ acornParse(code, { ...OPTS, onComment: (block, text, start, end) => { if (block && text.startsWith('*'))
298
+ comments.push({ text: `/*${text}*/`, start, end }); } });
299
+ const docBefore = (start) => {
300
+ let found;
301
+ for (const c of comments)
302
+ if (c.end <= start)
303
+ found = /\S/.test(code.slice(c.end, start)) ? undefined : c.text;
304
+ return found;
305
+ };
295
306
  const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
296
307
  const own = new Map();
308
+ const typedParam = new Map();
309
+ const typedBy = (doc, params) => {
310
+ const named = doc ? tags(doc).filter((t) => t.tag === 'param' && t.type && t.name && !t.name.includes('.')) : [];
311
+ 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]; };
312
+ };
297
313
  for (const stmt of ast.body) {
298
- if (stmt.type === 'FunctionDeclaration' && stmt.id)
314
+ if (stmt.type === 'FunctionDeclaration' && stmt.id) {
299
315
  own.set(stmt.id.name, stmt.params);
316
+ typedParam.set(stmt.id.name, typedBy(docBefore(stmt.start), stmt.params));
317
+ }
300
318
  if (stmt.type === 'VariableDeclaration')
301
319
  for (const d of stmt.declarations)
302
- if (d.id.type === 'Identifier' && isFn(d.init))
320
+ if (d.id.type === 'Identifier' && isFn(d.init)) {
303
321
  own.set(d.id.name, d.init.params);
322
+ typedParam.set(d.id.name, typedBy(docBefore(stmt.start), d.init.params));
323
+ }
304
324
  }
325
+ const edits = [];
305
326
  const targets = new Set();
327
+ const docs = new Map();
328
+ const typed = new Set();
306
329
  print(ast, code, (node, parent, key) => {
330
+ if (node.type === 'VariableDeclaration') {
331
+ const doc = docBefore(node.start);
332
+ const type = doc && tags(doc).find((t) => t.tag === 'type')?.type;
333
+ for (const d of node.declarations) {
334
+ if (type && d.id.type === 'Identifier' && node.declarations.length === 1) {
335
+ edits.push({ at: d.id.end, text: `: ${type}` });
336
+ if (isFn(d.init))
337
+ typed.add(d.init);
338
+ }
339
+ else if (doc && isFn(d.init))
340
+ docs.set(d.init, doc);
341
+ }
342
+ }
343
+ if (node.type === 'FunctionDeclaration' || (isFn(node) && parent?.type !== 'VariableDeclarator')) {
344
+ const doc = docBefore(parent?.type === 'MethodDefinition' ? parent.start : node.start);
345
+ if (doc)
346
+ docs.set(node, doc);
347
+ }
307
348
  if (node.type === 'FunctionDeclaration' || (isFn(node) && ((parent?.type === 'VariableDeclarator' && key === 'init') || parent?.type === 'MethodDefinition')))
308
349
  targets.add(node);
309
350
  const params = node.type === 'CallExpression' && node.callee.type === 'Identifier' ? own.get(node.callee.name) : undefined;
310
351
  if (params)
311
- node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern')
352
+ node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern' && !typedParam.get(node.callee.name)?.(i))
312
353
  targets.add(arg); });
313
354
  return undefined;
314
355
  });
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)
356
+ for (const fn of new Set([...targets, ...docs.keys()])) {
357
+ if (typed.has(fn))
358
+ continue;
359
+ const all = docs.has(fn) ? tags(docs.get(fn)) : [];
360
+ const params = all.filter((t) => t.tag === 'param' && t.name && !t.name.includes('.'));
361
+ const bareArrow = fn.type === 'ArrowFunctionExpression' && fn.params.length === 1 && !code.slice(fn.start, fn.params[0].start).includes('(');
362
+ const returns = all.find((t) => (t.tag === 'returns' || t.tag === 'return') && t.type)?.type;
363
+ let annotated = false;
364
+ fn.params.forEach((p, i) => {
365
+ const at = p.type === 'AssignmentPattern' ? p.left : p;
366
+ 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];
367
+ let type = tag?.type;
368
+ if (type && at.type === 'RestElement')
369
+ type = type.startsWith('...') ? `${type.slice(3)}[]` : type;
370
+ if (!type) {
371
+ if (!targets.has(fn) || p.type === 'AssignmentPattern')
372
+ return;
373
+ type = p.type === 'RestElement' ? 'any[]' : 'any';
374
+ }
375
+ if (bareArrow)
322
376
  edits.push({ at: p.start, text: '(' });
323
- edits.push({ at: p.end, text: (p.type === 'RestElement' ? ': any[]' : ': any') + (bare ? ')' : '') });
377
+ const optional = tag?.optional && at === p && p.type === 'Identifier' ? '?' : '';
378
+ edits.push({ at: at.end, text: `${optional}: ${type}${bareArrow ? `)${returns ? `: ${returns}` : ''}` : ''}` });
379
+ if (bareArrow)
380
+ annotated = true;
381
+ });
382
+ if (returns && bareArrow && !annotated)
383
+ edits.push({ at: fn.params[0].start, text: '(' }, { at: fn.params[0].end, text: `): ${returns}` });
384
+ if (returns && !bareArrow) {
385
+ const close = code.indexOf(')', fn.params.length ? fn.params[fn.params.length - 1].end : fn.start);
386
+ if (close !== -1 && close < fn.body.start)
387
+ edits.push({ at: close + 1, text: `: ${returns}` });
324
388
  }
325
389
  }
390
+ for (const c of comments) {
391
+ const types = typedefs(c.text);
392
+ if (types)
393
+ edits.push({ at: c.end, text: ` ${types}` });
394
+ }
326
395
  return edits.sort((a, b) => a.at - b.at);
327
396
  }
397
+ export function scriptTypeImports(code) {
398
+ const out = [];
399
+ acornParse(code, { ...OPTS, onComment: (block, text) => { if (block && text.startsWith('*'))
400
+ out.push(...jsdocImports(text)); } });
401
+ return out;
402
+ }
328
403
  const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
329
404
  export function analyzeScript(code, file, source, offset) {
330
405
  const signals = new Map();
@@ -448,7 +523,7 @@ export function providesIn(split, file, source, offset) {
448
523
  }
449
524
  const code = split.body;
450
525
  let found = false;
451
- const usage = "provide is called with a string key and a value: provide('tabs', { value })";
526
+ const usage = "provide is called with a key and a value: provide('tabs', { value }), or provide(tabsKey, { value }) with a key from contextKey()";
452
527
  const hook = (node, parent, key) => {
453
528
  if (node.type === 'Identifier' && node.name === 'provide' && !(parent?.type === 'CallExpression' && key === 'callee') && (!isBinding(parent, key) || parent?.shorthand)) {
454
529
  throw new ClarusError(usage, file, source, offset + node.start);
@@ -459,10 +534,11 @@ export function providesIn(split, file, source, offset) {
459
534
  if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'provide') {
460
535
  found = true;
461
536
  const key = node.arguments[0];
462
- if (!key || key.type !== 'Literal' || typeof key.value !== 'string' || node.arguments.length !== 2) {
537
+ const typed = key && (key.type === 'Identifier' || key.type === 'MemberExpression');
538
+ if (!key || (!typed && (key.type !== 'Literal' || typeof key.value !== 'string')) || node.arguments.length !== 2) {
463
539
  throw new ClarusError(usage, file, source, offset + node.start);
464
540
  }
465
- if (!/^[A-Za-z_$][\w$]*$/.test(key.value))
541
+ if (!typed && !/^[A-Za-z_$][\w$]*$/.test(key.value))
466
542
  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
543
  }
468
544
  return undefined;
@@ -476,6 +552,12 @@ function provideCall(node, rec) {
476
552
  const [key, value] = node.arguments;
477
553
  return `provide(${rec(key)}, () => (${rec(value)}))`;
478
554
  }
555
+ export const hasStatements = (code) => parseScript(code).body.length > 0;
556
+ export function provideGetters(code) {
557
+ const ast = parseScript(code);
558
+ const hook = (node) => provideCall(node, (n) => print(n, code, hook));
559
+ return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
560
+ }
479
561
  export function rewriteServer(code) {
480
562
  const ast = parseScript(code);
481
563
  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
+ };
@@ -0,0 +1,148 @@
1
+ import { Parser } from 'acorn';
2
+ import { tsPlugin } from '@sveltejs/acorn-typescript';
3
+ const TS = Parser.extend(tsPlugin());
4
+ const TYPE_KEYS = new Set(['typeAnnotation', 'returnType', 'typeParameters', 'typeArguments']);
5
+ const NEEDS_CODE = {
6
+ TSEnumDeclaration: 'an enum (use a union of strings, or an object with as const)',
7
+ TSModuleDeclaration: 'a namespace (use a module)',
8
+ TSParameterProperty: 'a constructor parameter property (assign it in the constructor)',
9
+ TSImportEqualsDeclaration: 'import … = require(…)',
10
+ TSExportAssignment: 'export =',
11
+ };
12
+ function names(p) {
13
+ if (!p)
14
+ return [];
15
+ if (p.type === 'Identifier')
16
+ return [p.name];
17
+ if (p.type === 'ObjectPattern')
18
+ return p.properties.flatMap((x) => names(x.type === 'RestElement' ? x.argument : x.value));
19
+ if (p.type === 'ArrayPattern')
20
+ return p.elements.flatMap((x) => names(x));
21
+ if (p.type === 'AssignmentPattern')
22
+ return names(p.left);
23
+ if (p.type === 'RestElement')
24
+ return names(p.argument);
25
+ return [];
26
+ }
27
+ export class StripError extends Error {
28
+ pos;
29
+ constructor(message, pos) { super(message); this.pos = pos; }
30
+ }
31
+ export function stripTypes(code) {
32
+ let ast;
33
+ try {
34
+ ast = TS.parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
35
+ }
36
+ catch (e) {
37
+ throw new StripError(`script: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, e.pos ?? 0);
38
+ }
39
+ const out = code.split('');
40
+ const blank = (from, to) => { for (let i = from; i < to; i++)
41
+ if (out[i] !== '\n')
42
+ out[i] = ' '; };
43
+ const typeImports = [];
44
+ const commaAfter = (from) => {
45
+ for (let i = from; i < code.length;) {
46
+ if (/\s/.test(code[i]))
47
+ i++;
48
+ else if (code.startsWith('/*', i)) {
49
+ const e = code.indexOf('*/', i + 2);
50
+ i = e === -1 ? code.length : e + 2;
51
+ }
52
+ else if (code.startsWith('//', i)) {
53
+ const n = code.indexOf('\n', i);
54
+ i = n === -1 ? code.length : n;
55
+ }
56
+ else
57
+ return code[i] === ',' ? i : -1;
58
+ }
59
+ return -1;
60
+ };
61
+ const blankSpecifiers = (specs, all) => {
62
+ for (const s of specs) {
63
+ const after = commaAfter(s.end);
64
+ if (after !== -1) {
65
+ blank(s.start, after + 1);
66
+ continue;
67
+ }
68
+ const prev = all[all.indexOf(s) - 1];
69
+ const before = prev ? commaAfter(prev.end) : -1;
70
+ blank(s.start, s.end);
71
+ if (before !== -1 && out[before] === ',')
72
+ blank(before, before + 1);
73
+ }
74
+ };
75
+ const visit = (node, parent) => {
76
+ if (NEEDS_CODE[node.type] && !node.declare)
77
+ throw new StripError(`TypeScript that needs generated code isn't supported in a <script lang="ts">: ${NEEDS_CODE[node.type]}`, node.start);
78
+ if (node.abstract || node.accessibility || node.override || (node.readonly && parent?.type === 'ClassBody') || node.decorators?.length) {
79
+ throw new StripError('class modifiers (public, private, protected, readonly, abstract, override) and decorators aren\'t supported in a <script lang="ts">', node.start);
80
+ }
81
+ if (node.type === 'TSInterfaceDeclaration' || node.type === 'TSTypeAliasDeclaration' || node.type === 'TSDeclareFunction' || (node.declare && node.type !== 'PropertyDefinition') || ((node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') && node.exportKind === 'type')) {
82
+ return blank(node.start, node.end);
83
+ }
84
+ if (node.type === 'ImportDeclaration') {
85
+ if (node.importKind === 'type') {
86
+ typeImports.push({ text: code.slice(node.start, node.end), start: node.start });
87
+ return blank(node.start, node.end);
88
+ }
89
+ const types = node.specifiers.filter((s) => s.importKind === 'type');
90
+ if (types.length)
91
+ typeImports.push({ text: `import type { ${types.map((s) => code.slice(s.start, s.end).replace(/^type\s+/, '')).join(', ')} } from ${code.slice(node.source.start, node.source.end)}`, start: node.start });
92
+ blankSpecifiers(types, node.specifiers);
93
+ return;
94
+ }
95
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers?.length)
96
+ blankSpecifiers(node.specifiers.filter((s) => s.exportKind === 'type'), node.specifiers);
97
+ if (node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')
98
+ blank(node.expression.end, node.end);
99
+ else if (node.type === 'TSNonNullExpression')
100
+ blank(node.end - 1, node.end);
101
+ else if (node.type === 'TSTypeAssertion')
102
+ blank(node.start, node.expression.start);
103
+ if ((node.type === 'Identifier' && node.optional) || (node.type === 'VariableDeclarator' && node.definite)) {
104
+ const at = node.type === 'Identifier' ? node.start + node.name.length : node.id.start + (node.id.name?.length ?? 0);
105
+ const mark = code.slice(at).search(/[?!]/);
106
+ if (mark !== -1)
107
+ blank(at + mark, at + mark + 1);
108
+ }
109
+ if (node.implements?.length) {
110
+ const first = node.implements[0];
111
+ blank(code.lastIndexOf('implements', first.start), node.implements.at(-1).end);
112
+ }
113
+ for (const key of Object.keys(node)) {
114
+ if (key === 'loc')
115
+ continue;
116
+ const value = node[key];
117
+ const children = Array.isArray(value) ? value : [value];
118
+ for (const child of children) {
119
+ if (!child || typeof child.type !== 'string')
120
+ continue;
121
+ if (TYPE_KEYS.has(key) && child.type.startsWith('TS'))
122
+ blank(child.start, child.end);
123
+ else if (key === 'implements')
124
+ continue;
125
+ else if (!(node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression' || node.type === 'TSTypeAssertion') || key === 'expression')
126
+ visit(child, node);
127
+ }
128
+ }
129
+ };
130
+ visit(ast);
131
+ const top = ast.body.map((s) => (s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s));
132
+ const values = top.flatMap((s) => (s.type === 'VariableDeclaration' ? s.declarations.flatMap((d) => names(d.id)) : (s.type === 'FunctionDeclaration' || s.type === 'ClassDeclaration') && s.id ? [s.id.name] : []));
133
+ const outer = new Map(ast.body.filter((s) => s.type === 'ExportNamedDeclaration' && s.declaration).map((s) => [s.declaration, s]));
134
+ const decls = top.filter((s) => s.type === 'TSInterfaceDeclaration' || s.type === 'TSTypeAliasDeclaration').map((s) => { const w = outer.get(s) ?? s; return { name: s.id.name, text: code.slice(w.start, w.end), start: w.start }; });
135
+ const word = (w) => new RegExp(`(?<![\\w$.])${w.replace(/\$/g, '\\$')}(?![\\w$])`);
136
+ const stays = new Set(decls.filter((d) => values.some((v) => new RegExp(`\\btypeof\\s+${v.replace(/\$/g, '\\$')}(?![\\w$])`).test(d.text))).map((d) => d.name));
137
+ for (let grew = true; grew;) {
138
+ grew = false;
139
+ for (const d of decls)
140
+ if (!stays.has(d.name) && [...stays].some((s) => word(s).test(d.text.slice(d.text.indexOf(d.name) + d.name.length)))) {
141
+ stays.add(d.name);
142
+ grew = true;
143
+ }
144
+ }
145
+ const typeDecls = decls.filter((d) => !stays.has(d.name)).map(({ text, start }) => ({ text, start }));
146
+ const stayingExports = [...outer].filter(([d]) => stays.has(d.id?.name)).map(([, s]) => s.start);
147
+ return { code: out.join(''), typeImports, typeDecls, stayingExports };
148
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A context's name, with its value's type (type checking only). Provide with it, `provide(tabs, { value })`, and read
3
+ * with it, `const tabs = context(tabsKey)`; a value of another shape is a type error on either side.
4
+ * @see https://clarusjs.com/guide/context#typed-keys
5
+ */
6
+ export type ContextKey<T> = {
7
+ readonly name: string; /** Islands may read it: its value is written into the page. */
8
+ readonly public?: true; /** The value's type, for type checking (never set). */
9
+ readonly __clContext?: T;
10
+ };
11
+ /**
12
+ * A typed context key, to export from a `.ts` module that the providing and the reading components both import.
13
+ * `{ public: true }` lets islands read it: an island's context is written into the page (its HTML), so it's opt-in, on
14
+ * the key, where the type is; a component without a script reads any context.
15
+ * @example
16
+ * ```ts
17
+ * // src/context.ts
18
+ * import { contextKey } from 'clarusjs/runtime'
19
+ * export const tabsKey = contextKey<{ value: string }>('tabs')
20
+ * export const themeKey = contextKey<'light' | 'dark'>('theme', { public: true }) // islands may read it
21
+ * ```
22
+ * @see https://clarusjs.com/reference/runtime#contextkey
23
+ */
24
+ export declare function contextKey<T>(name: string, options: {
25
+ public: true;
26
+ }): ContextKey<T> & {
27
+ readonly public: true;
28
+ };
29
+ export declare function contextKey<T>(name: string, options?: {
30
+ public?: false;
31
+ }): ContextKey<T>;
@@ -0,0 +1,4 @@
1
+ // Typed context keys: one name and one type shared by the components that provide a value and those that read it.
2
+ export function contextKey(name, options) {
3
+ return options?.public === true ? { name, public: true } : { name }; // exactly true: a stray "false" isn't consent
4
+ }
@@ -4,3 +4,4 @@ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
5
  export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
6
6
  export { browser } from './env.ts';
7
+ export { contextKey, type ContextKey } from './context.ts';
@@ -5,3 +5,4 @@ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './
5
5
  export { parse as parseIslandData } from './serialize.js';
6
6
  export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.js';
7
7
  export { browser } from './env.js';
8
+ export { contextKey } from './context.js';