@mylasertools/kerfscript 0.7.0 → 0.8.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.
- package/CHANGELOG.md +34 -0
- package/LANGUAGE.md +16 -7
- package/dist/cli.js +205 -18
- package/dist/geometry.d.cts +5 -0
- package/dist/geometry.d.ts +5 -0
- package/dist/highlight.cjs +1 -1
- package/dist/highlight.js +1 -1
- package/dist/index.cjs +383 -46
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +383 -46
- package/dist/language.cjs +381 -44
- package/dist/language.js +381 -44
- package/dist/libraries.cjs +353 -16
- package/dist/libraries.js +351 -14
- package/dist/signatures.cjs +29 -4
- package/dist/signatures.js +29 -4
- package/dist/verify/solids.d.cts +2 -1
- package/dist/verify/solids.d.ts +2 -1
- package/dist/verify/types.d.cts +2 -0
- package/dist/verify/types.d.ts +2 -0
- package/docs/library.md +206 -4
- package/docs/parts-and-sheets.md +31 -18
- package/docs/versions.md +2 -2
- package/package.json +1 -1
package/dist/libraries.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/*! @mylasertools/kerfscript | (c) MyLaserTools | AGPL-3.0-only or commercial licence, see COMMERCIAL-LICENSE.md. Includes Clipper2 (BSL-1.0), opentype.js, tiny-inflate and string.prototype.codepointat (MIT), see THIRD-PARTY-NOTICES.md. */
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var B=Object.defineProperty;var z1=Object.getOwnPropertyDescriptor;var f1=Object.getOwnPropertyNames;var u1=Object.prototype.hasOwnProperty;var p1=(a,c)=>{for(var l in c)B(a,l,{get:c[l],enumerable:!0})},g1=(a,c,l,e)=>{if(c&&typeof c=="object"||typeof c=="function")for(let n of f1(c))!u1.call(a,n)&&n!==l&&B(a,n,{get:()=>c[n],enumerable:!(e=z1(c,n))||e.enumerable});return a};var b1=a=>g1(B({},"__esModule",{value:!0}),a);var Z1={};p1(Z1,{FOLDER:()=>A,LOCK:()=>H,LibraryError:()=>R,MANIFEST:()=>u,add:()=>$1,check:()=>T1,findProject:()=>X,install:()=>M1,installedPaths:()=>H1,integrity:()=>T,libraryFile:()=>o1,pack:()=>R1,readLock:()=>Y,readManifest:()=>k,remove:()=>P1,resolver:()=>C1});module.exports=b1(Z1);var r1=require("node:crypto"),z=require("node:fs"),m=require("node:path"),E=require("node:zlib");var w1=(a,c=!0)=>`line ${a.line}${c?`, column ${a.col}`:""}${a.file?` in <${a.file}>`:""}`;var C=class extends Error{constructor(l,e){super(e?`${l} (${w1(e)})`:l);this.echoes=[];this.warnings=[];this.trace=[];this.traceMore=0;this.name="KerfError",this.reason=l,e&&(this.line=e.line,this.col=e.col,this.file=e.file)}addFrame(l,e,n){let t=this.trace.find(h=>h.name===e&&h.line===n.line&&h.col===n.col&&h.file===n.file);t?t.count++:this.trace.length>=50?this.traceMore++:this.trace.push({kind:l,name:e,line:n.line,col:n.col,...n.file&&{file:n.file},count:1})}},L1=["<=",">=","==","!=","&&","||","+","-","*","/","%","^","<",">","!","?",":","=",".",",",";","(",")","[","]","{","}","#"];function n1(a,c){let l=[],e=[],n=0,t=1,h=0,s=()=>({line:t,col:n-h+1,offset:n,...c&&{file:c}}),i=o=>{for(let M=0;M<o;M++)a[n]===`
|
|
3
3
|
`&&(t++,h=n+1),n++};for(;n<a.length;){let o=a[n];if(o===" "||o===" "||o==="\r"||o===`
|
|
4
4
|
`){i(1);continue}if(o==="/"&&a[n+1]==="/"){let r=a.indexOf(`
|
|
5
5
|
`,n),v=r<0?a.length:r,g=/^[ \t]*$/.test(a.slice(a.lastIndexOf(`
|
|
6
|
-
`,n-1)+1,n));e.push({text:a.slice(n+2,v).trim(),line:t,block:!1,own:g,start:n,end:v}),n=v;continue}if(o==="/"&&a[n+1]==="*"){let r=s(),v=a.indexOf("*/",n+2);if(v<0)throw new
|
|
7
|
-
`;else if(v==="t")r+=" ";else if(v==="u"){let g=a.slice(n+2,n+6);if(!/^[0-9a-fA-F]{4}$/.test(g))throw new
|
|
8
|
-
`)throw new
|
|
6
|
+
`,n-1)+1,n));e.push({text:a.slice(n+2,v).trim(),line:t,block:!1,own:g,start:n,end:v}),n=v;continue}if(o==="/"&&a[n+1]==="*"){let r=s(),v=a.indexOf("*/",n+2);if(v<0)throw new C("Unclosed block comment",r);e.push({text:a.slice(n+2,v).trim(),line:r.line,block:!0,own:!0,start:n,end:v+2}),i(v+2-n);continue}let M=s();if(/[0-9]/.test(o)||o==="."&&/[0-9]/.test(a[n+1]??"")){let r=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?(?:(?:mm|cm|m|in|ft)(?![A-Za-z0-9_]))?/.exec(a.slice(n));l.push({type:"num",value:r[0],pos:M,end:n+r[0].length}),i(r[0].length);continue}if(/[A-Za-z_$]/.test(o)){let r=/^[A-Za-z_$][A-Za-z0-9_]*/.exec(a.slice(n));l.push({type:"id",value:r[0],pos:M,end:n+r[0].length}),i(r[0].length);continue}if(o==='"'){let r="";for(i(1);n<a.length&&a[n]!=='"';){if(a[n]==="\\"){let v=a[n+1];if(v==="n")r+=`
|
|
7
|
+
`;else if(v==="t")r+=" ";else if(v==="u"){let g=a.slice(n+2,n+6);if(!/^[0-9a-fA-F]{4}$/.test(g))throw new C("Bad \\u escape",s());r+=String.fromCharCode(parseInt(g,16)),i(4)}else r+=v;i(2);continue}if(a[n]===`
|
|
8
|
+
`)throw new C("Unclosed string",M);r+=a[n],i(1)}if(n>=a.length)throw new C("Unclosed string",M);i(1),l.push({type:"str",value:r,pos:M,end:n});continue}if(o==="<"&&/^<[A-Za-z0-9_./-]+>/.test(a.slice(n))){let r=l[l.length-1];if(r&&r.type==="id"&&(r.value==="use"||r.value==="include")){let v=/^<([A-Za-z0-9_./-]+)>/.exec(a.slice(n));l.push({type:"str",value:v[1],pos:M,end:n+v[0].length}),i(v[0].length);continue}}let f=L1.find(r=>a.startsWith(r,n));if(!f)throw new C(`Unexpected character "${o}"`,M);l.push({type:"punct",value:f,pos:M,end:n+f.length}),i(f.length)}return l.push({type:"eof",value:"",pos:s(),end:n}),{tokens:l,comments:e}}var K=new Set(["module","function","if","else","for","let","each","use","include","true","false","undef"]);function e1(a,c){let{tokens:l,comments:e}=n1(a,c),n=new D(l),t=[];for(;!n.at("eof");)t.push(...n.statement());return{program:{body:t},comments:e}}var D=class a{constructor(c){this.tokens=c;this.i=0}peek(c=0){return this.tokens[Math.min(this.i+c,this.tokens.length-1)]}at(c,l,e=0){let n=this.peek(e);return n.type===c&&(l===void 0||n.value===l)}isP(c,l=0){return this.at("punct",c,l)}isK(c,l=0){return this.at("id",c,l)}next(){return this.tokens[this.i++]}fail(c,l=this.peek()){let e=l.type==="eof"?"end of file":`"${l.value}"`;throw new C(`${c}, found ${e}`,l.pos)}expectP(c){return this.isP(c)||this.fail(`Expected "${c}"`),this.next()}separator(c){this.isP(c)||(this.isP(",")||this.fail(`Expected "," or "${c}"`),this.next())}ident(){let c=this.peek();return(c.type!=="id"||K.has(c.value))&&this.fail("Expected a name"),this.next()}last(){return this.tokens[this.i-1].end}statement(){let c=this.stmt();for(let l of c)l.end=this.last();return c}stmt(){let c=this.peek();if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let h=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),h.push(...this.statement());return this.next(),[{kind:"block",body:h,pos:c.pos}]}if(this.isK("module")){this.next();let h=this.ident(),s=this.params();return[{kind:"module",name:h.value,params:s,body:this.body(),pos:c.pos,namePos:h.pos}]}if(this.isK("function")&&this.at("id",void 0,1)){this.next();let h=this.ident(),s=this.params();this.expectP("=");let i=this.expr();return this.expectP(";"),[{kind:"function",name:h.value,params:s,body:i,pos:c.pos,namePos:h.pos}]}if(this.isK("use")||this.isK("include")){this.next();let h=this.peek();return h.type!=="str"&&this.fail("Expected a library path like <kerf/box>"),this.next(),this.isP(";")&&this.next(),[{kind:"use",path:h.value,include:c.value==="include",pos:c.pos}]}if(this.isK("for"))return this.next(),[{kind:"for",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(this.isK("if")){this.next(),this.expectP("(");let h=this.expr();this.expectP(")");let s=this.body(),i=[];return this.isK("else")&&(this.next(),i=this.body()),[{kind:"if",cond:h,then:s,else:i,pos:c.pos}]}if(this.isK("let")&&this.isP("(",1))return this.next(),[{kind:"let",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(c.type==="id"&&this.isP("=",1)){let h=this.ident().value;this.next();let s=this.peek().pos.offset,i=this.expr(),o=this.expectP(";").pos.offset;return[{kind:"assign",name:h,value:i,span:[s,o],pos:c.pos}]}let l=null;(this.isP("*")||this.isP("!")||this.isP("#")||this.isP("%"))&&(l=this.next().value);let e=this.peek();(e.type!=="id"||K.has(e.value))&&this.fail("Expected a statement"),this.next();let n=this.args(),t=this.body();return[{kind:"call",name:e.value,args:n,children:t,modifier:l,pos:e.pos}]}body(){if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let c=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),c.push(...this.statement());return this.next(),c}return this.statement()}params(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident(),e=null;this.isP("=")&&(this.next(),e=this.expr()),c.push({name:l.value,default:e,pos:l.pos}),this.separator(")")}return this.next(),c}args(){this.expectP("(");let c=[];for(;!this.isP(")");){if(this.at("id")&&this.isP("=",1)){let l=this.next();this.next(),c.push({name:l.value,value:this.expr(),pos:l.pos})}else c.push({name:null,value:this.expr()});this.separator(")")}return this.next(),c}assigns(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident();this.expectP("="),c.push({name:l.value,value:this.expr(),pos:l.pos}),this.separator(")")}return this.next(),c}expr(){let c=this.peek();if(this.isK("function")&&this.isP("(",1)){this.next();let e=this.params(),n=this.expr();return{kind:"lambda",params:e,body:n,pos:c.pos,end:this.last()}}if(this.isK("let")&&this.isP("(",1)){this.next();let e=this.assigns(),n=this.expr();return{kind:"let",assigns:e,body:n,pos:c.pos,end:this.last()}}let l=this.binary(0);if(this.isP("?")){this.next();let e=this.expr();this.expectP(":");let n=this.expr();return{kind:"ternary",cond:l,then:e,else:n,pos:c.pos}}return l}static{this.LEVELS=[["||"],["&&"],["==","!="],["<","<=",">",">="],["+","-"],["*","/","%"]]}binary(c){if(c>=a.LEVELS.length)return this.unary();let l=this.binary(c+1);for(;this.at("punct")&&a.LEVELS[c].includes(this.peek().value);){let e=this.next(),n=this.binary(c+1);l={kind:"binary",op:e.value,left:l,right:n,pos:e.pos}}return l}unary(){if(this.isP("-")||this.isP("!")||this.isP("+")){let c=this.next();return{kind:"unary",op:c.value,arg:this.unary(),pos:c.pos}}return this.power()}power(){let c=this.postfix();if(this.isP("^")){let l=this.next();return{kind:"binary",op:"^",left:c,right:this.unary(),pos:l.pos}}return c}postfix(){let c=this.primary();for(;;){let l=this.peek();if(this.isP("("))c={kind:"call",callee:c,args:this.args(),pos:c.pos};else if(this.isP("[")){this.next();let e=this.expr();this.expectP("]"),c={kind:"index",target:c,index:e,pos:l.pos}}else if(this.isP("."))this.next(),c={kind:"member",target:c,name:this.ident().value,pos:l.pos};else return c}}primary(){let c=this.peek();if(c.type==="num"){this.next();let l=/(mm|cm|m|in|ft)$/.exec(c.value);return l?{kind:"num",value:Number(c.value.slice(0,-l[1].length)),unit:l[1],pos:c.pos}:{kind:"num",value:Number(c.value),pos:c.pos}}if(c.type==="str")return this.next(),{kind:"str",value:c.value,pos:c.pos};if(c.type==="id")return c.value==="true"||c.value==="false"?(this.next(),{kind:"bool",value:c.value==="true",pos:c.pos}):c.value==="undef"?(this.next(),{kind:"undef",pos:c.pos}):(K.has(c.value)&&this.fail("Expected a value"),this.next(),{kind:"var",name:c.value,pos:c.pos});if(this.isP("(")){this.next();let l=this.expr();return this.expectP(")"),l}if(this.isP("["))return this.list();if(this.isP("{"))return this.record();this.fail("Expected a value")}record(){let c=this.expectP("{"),l=[];for(;!this.isP("}");){let e=this.ident();if(l.some(n=>n.name===e.value))throw new C(`Field ${e.value} is given twice`,e.pos);if(this.expectP("="),l.push({name:e.value,value:this.expr(),pos:e.pos}),!this.isP(","))break;this.next()}return this.expectP("}"),{kind:"record",fields:l,pos:c.pos}}list(){let c=this.expectP("[");if(this.isP("]"))return this.next(),{kind:"list",items:[],pos:c.pos};if(!this.isK("for")&&!this.isK("if")&&!this.isK("each")&&!(this.isK("let")&&this.isP("(",1))&&!(this.isP("(")&&(this.isK("for",1)||this.isK("if",1)))){let l=this.expr();if(this.isP(":")){this.next();let n=null,t=this.expr();return this.isP(":")&&(this.next(),n=t,t=this.expr()),this.expectP("]"),{kind:"range",start:l,step:n,end:t,pos:c.pos}}let e=[{kind:"item",expr:l}];return this.listRest(e,c.pos)}return this.listRest([],c.pos)}listRest(c,l){if(c.length){if(this.isP("]"))return this.next(),{kind:"list",items:c,pos:l};this.separator("]")}for(;!this.isP("]");)c.push(this.listItem()),this.separator("]");return this.next(),{kind:"list",items:c,pos:l}}listItem(){let c=this.peek();if(this.isK("for")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"for",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("if")&&this.isP("(",1)){this.next(),this.expectP("(");let l=this.expr();this.expectP(")");let e=this.listItem(),n=null;return this.isK("else")&&(this.next(),n=this.listItem()),{kind:"if",cond:l,then:e,else:n}}if(this.isK("let")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"let",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("each"))return this.next(),{kind:"each",expr:this.expr()};if(this.isP("(")&&(this.isK("for",1)||this.isK("if",1))){this.next();let l=this.listItem();return this.expectP(")"),l}return{kind:"item",expr:this.expr()}}};var t1={"kerf/box":`// kerf/box: finger-jointed boxes.
|
|
9
9
|
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
10
10
|
|
|
11
11
|
// Box from its outer size [width, depth, height] in the current material.
|
|
@@ -97,6 +97,62 @@ module joint_test(kerfs = [0.1, 0.15, 0.2], size = [40, 20], finger = undef, lab
|
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
+
`,"kerf/cones":`// kerf/cones: cones and cut-off cones cut flat, to roll up from thin sheet.
|
|
101
|
+
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
102
|
+
//
|
|
103
|
+
// A cone rolled from paper, card, veneer or thin plastic is a ring sector
|
|
104
|
+
// when flat. Gramophone horns, lampshades, funnels and party hats all start
|
|
105
|
+
// as one. The sector's apex is at the origin and it opens from +x
|
|
106
|
+
// anticlockwise; the glue tab runs along its far edge.
|
|
107
|
+
|
|
108
|
+
// The flat pattern of a cone of radius r1 at one end, r2 at the other and h
|
|
109
|
+
// high: [outer radius, inner radius, angle in degrees, slant length]. A
|
|
110
|
+
// cylinder (r1 == r2) has no apex: it gives [undef, undef, 0, h] and is a
|
|
111
|
+
// rectangle 2 * PI * r1 wide.
|
|
112
|
+
function cone_pattern(r1, r2, h) =
|
|
113
|
+
let (
|
|
114
|
+
big = max(r1, r2),
|
|
115
|
+
small = min(r1, r2),
|
|
116
|
+
s = sqrt(h * h + pow(big - small, 2))
|
|
117
|
+
)
|
|
118
|
+
big == small ? [undef, undef, 0, h]
|
|
119
|
+
: [s * big / (big - small), s * small / (big - small), 360 * (big - small) / s, s];
|
|
120
|
+
|
|
121
|
+
// A cone or cut-off cone cut flat: rolled up so the far edge lies on the
|
|
122
|
+
// glue tab, it has radius r1 at one end, r2 at the other, and is h high.
|
|
123
|
+
// \`tab\` adds a glue tab that wide along the far edge, its fold scored; a
|
|
124
|
+
// cylinder becomes a rectangle with the tab on its right.
|
|
125
|
+
module cone_flat(r1, r2, h, tab = 0, steps = 0) {
|
|
126
|
+
p = cone_pattern(r1, r2, h);
|
|
127
|
+
if (is_undef(p[0])) {
|
|
128
|
+
w = 2 * PI * r1;
|
|
129
|
+
rect([w, h]);
|
|
130
|
+
if (tab > 0) {
|
|
131
|
+
polygon([[w, 0], [w + tab, min(tab, h / 4)], [w + tab, h - min(tab, h / 4)], [w, h]]);
|
|
132
|
+
score() line([w, 0], [w, h]);
|
|
133
|
+
}
|
|
134
|
+
} else {
|
|
135
|
+
a = p[2];
|
|
136
|
+
n = steps > 0 ? steps : max(8, ceil(a / 3));
|
|
137
|
+
arc_pts = function(r) [for (i = [0:n]) [r * cos(a * i / n), r * sin(a * i / n)]];
|
|
138
|
+
polygon(concat(arc_pts(p[0]), p[1] > 0 ? reverse(arc_pts(p[1])) : [[0, 0]]));
|
|
139
|
+
if (tab > 0) {
|
|
140
|
+
// The tab beyond the far edge, its ends cut in so it hides when rolled
|
|
141
|
+
ux = cos(a);
|
|
142
|
+
uy = sin(a);
|
|
143
|
+
nx = -uy;
|
|
144
|
+
ny = ux;
|
|
145
|
+
c = min(tab, p[3] / 4);
|
|
146
|
+
polygon([
|
|
147
|
+
[p[1] * ux, p[1] * uy],
|
|
148
|
+
[p[0] * ux, p[0] * uy],
|
|
149
|
+
[(p[0] - c) * ux + tab * nx, (p[0] - c) * uy + tab * ny],
|
|
150
|
+
[(p[1] + (p[1] > 0 ? c : tab)) * ux + tab * nx, (p[1] + (p[1] > 0 ? c : tab)) * uy + tab * ny],
|
|
151
|
+
]);
|
|
152
|
+
score() line([p[1] * ux, p[1] * uy], [p[0] * ux, p[0] * uy]);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
100
156
|
`,"kerf/dividers":`// kerf/dividers: dividers that slot into each other like an egg crate.
|
|
101
157
|
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
102
158
|
|
|
@@ -370,6 +426,209 @@ module tappets(n, r, w = 10, hub = 14, bore = 6, square = false) {
|
|
|
370
426
|
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
371
427
|
}
|
|
372
428
|
}
|
|
429
|
+
|
|
430
|
+
// Cams from a lift curve. The follower rides on the cam's top (+y) and
|
|
431
|
+
// moves straight up and down; turned anticlockwise by \`a\` degrees (rotate =
|
|
432
|
+
// [0, 0, a]), the cam lifts it lift(a) above the base circle. \`lift\` is a
|
|
433
|
+
// function of the angle, 0 to 360, that comes back to where it started.
|
|
434
|
+
|
|
435
|
+
// A smooth rise of \`height\` from angle a0 to a1 (cycloidal: it starts and
|
|
436
|
+
// stops gently): 0 before a0, height after a1. Add and take away rises to
|
|
437
|
+
// make dwells, rises and falls: two pecks then a rest is
|
|
438
|
+
// function(a) cam_rise(a, 0, 40, 8) - cam_rise(a, 40, 80, 8) + cam_rise(a, 100, 140, 8) - cam_rise(a, 140, 180, 8).
|
|
439
|
+
function cam_rise(a, a0, a1, height) =
|
|
440
|
+
a <= a0 ? 0
|
|
441
|
+
: a >= a1 ? height
|
|
442
|
+
: let (u = (a - a0) / (a1 - a0)) height * (u - sin(360 * u) / (2 * PI));
|
|
443
|
+
|
|
444
|
+
// The cam's pitch curve: where the follower's tip (or its roller's centre)
|
|
445
|
+
// sits, in the cam's own turn, \`steps\` points round
|
|
446
|
+
function cam_pitch(lift, base_r, roller_d = 0, steps = 180) =
|
|
447
|
+
[for (i = [0:steps - 1])
|
|
448
|
+
let (f = i * 360 / steps, a = (450 - f) % 360, r = base_r + roller_d / 2 + lift(a))
|
|
449
|
+
[r * cos(f), r * sin(f)]];
|
|
450
|
+
|
|
451
|
+
// How high the follower's tip (or its roller's centre) is above the cam's
|
|
452
|
+
// axle when the cam is turned to \`angle\`, to place the follower
|
|
453
|
+
function cam_follower(lift, base_r, angle, roller_d = 0) =
|
|
454
|
+
base_r + roller_d / 2 + lift(((angle % 360) + 360) % 360);
|
|
455
|
+
|
|
456
|
+
// The steepest pressure angle over a turn, in degrees: how hard the cam
|
|
457
|
+
// pushes the follower sideways. Keep it under about 30, by a bigger base
|
|
458
|
+
// circle or a longer rise.
|
|
459
|
+
function cam_pressure(lift, base_r, roller_d = 0, steps = 360) =
|
|
460
|
+
max([for (i = [0:steps - 1])
|
|
461
|
+
let (
|
|
462
|
+
a = i * 360 / steps,
|
|
463
|
+
r = base_r + roller_d / 2 + lift(a),
|
|
464
|
+
slope = (lift((a + 0.5) % 360) - lift((a + 359.5) % 360)) / (PI / 180)
|
|
465
|
+
)
|
|
466
|
+
atan(abs(slope) / r)]);
|
|
467
|
+
|
|
468
|
+
// A cam that lifts a follower lift(a) at angle a, with a hole for its
|
|
469
|
+
// axle. A "knife" follower rides the pitch curve itself; a "roller" one of
|
|
470
|
+
// diameter roller_d rolls on a profile inside it. Check cam_pressure().
|
|
471
|
+
module cam(lift, base_r, follower = "knife", roller_d = 0, bore = 6, steps = 180, square = false) {
|
|
472
|
+
assert(follower == "knife" || follower == "roller", "follower must be \\"knife\\" or \\"roller\\"");
|
|
473
|
+
assert(follower == "knife" || roller_d > 0, "a roller follower needs roller_d");
|
|
474
|
+
difference() {
|
|
475
|
+
if (follower == "roller") offset(r = -roller_d / 2) polygon(cam_pitch(lift, base_r, roller_d, steps));
|
|
476
|
+
else polygon(cam_pitch(lift, base_r, 0, steps));
|
|
477
|
+
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// A Geneva drive: a driver turning all the time steps a wheel of \`slots\`
|
|
482
|
+
// slots on by one slot each turn, and locks it between steps. The driver's
|
|
483
|
+
// axle is at the origin and the wheel's at [distance, 0]. Cut the wheel and
|
|
484
|
+
// the locking disc from the same sheet, side by side in one plane, and the
|
|
485
|
+
// crank above them; a dowel pin of pin_d through the crank's outer hole
|
|
486
|
+
// runs in the wheel's slots.
|
|
487
|
+
|
|
488
|
+
// The radius of the circle the driver's pin turns on
|
|
489
|
+
function geneva_pin_radius(slots, distance) = distance * sin(180 / slots);
|
|
490
|
+
// The wheel's outer radius
|
|
491
|
+
function geneva_wheel_radius(slots, distance, pin_d) =
|
|
492
|
+
sqrt(pow(distance * cos(180 / slots), 2) + pow(pin_d / 2, 2));
|
|
493
|
+
// The locking disc's radius
|
|
494
|
+
function geneva_lock_radius(slots, distance, pin_d) = geneva_pin_radius(slots, distance) - pin_d;
|
|
495
|
+
|
|
496
|
+
// How far the wheel has turned when the driver has turned \`angle\`
|
|
497
|
+
// anticlockwise from its pin pointing at the wheel: it turns clockwise,
|
|
498
|
+
// 360 / slots each turn of the driver, and stands still between steps
|
|
499
|
+
function geneva_turn(slots, distance, angle) =
|
|
500
|
+
let (
|
|
501
|
+
k = floor((angle + 180) / 360),
|
|
502
|
+
t = angle - 360 * k,
|
|
503
|
+
rc = geneva_pin_radius(slots, distance),
|
|
504
|
+
on = 90 - 180 / slots,
|
|
505
|
+
step = abs(t) <= on ? atan2(-rc * sin(t), distance - rc * cos(t))
|
|
506
|
+
: t < 0 ? 180 / slots : -180 / slots
|
|
507
|
+
)
|
|
508
|
+
step - k * 360 / slots;
|
|
509
|
+
|
|
510
|
+
// The wheel, centred on the origin, a slot along -x (towards the driver
|
|
511
|
+
// when geneva_turn() is 0)
|
|
512
|
+
module geneva_wheel(slots, distance, pin_d = 6, bore = 6, clearance = 0.2, square = false) {
|
|
513
|
+
rc = geneva_pin_radius(slots, distance);
|
|
514
|
+
ro = geneva_wheel_radius(slots, distance, pin_d);
|
|
515
|
+
rl = geneva_lock_radius(slots, distance, pin_d);
|
|
516
|
+
w = pin_d + clearance;
|
|
517
|
+
inner = distance - rc - clearance;
|
|
518
|
+
assert(rl > 0, "the pin is too thick to leave a locking disc: make the distance longer or the pin thinner");
|
|
519
|
+
assert(inner - w / 2 > bore / 2 + 3, "the slots reach the axle: use more slots, a longer distance or a smaller bore");
|
|
520
|
+
difference() {
|
|
521
|
+
circle(r = ro);
|
|
522
|
+
for (j = [0:slots - 1]) rotate(180 + j * 360 / slots) {
|
|
523
|
+
hull() {
|
|
524
|
+
translate([inner, 0]) circle(d = w);
|
|
525
|
+
translate([ro + 1, -w / 2]) rect([1, w]);
|
|
526
|
+
}
|
|
527
|
+
// The locking arc between this slot and the next
|
|
528
|
+
rotate(180 / slots) translate([distance, 0]) circle(r = rl + clearance);
|
|
529
|
+
}
|
|
530
|
+
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// The locking disc that turns with the driver, its relief facing the pin's
|
|
535
|
+
// side (+x): cut away wherever the wheel's rim passes while the pin is in a
|
|
536
|
+
// slot, so the wheel turns then
|
|
537
|
+
module geneva_lock(slots, distance, pin_d = 6, bore = 6, clearance = 0.2, square = false) {
|
|
538
|
+
assert(geneva_lock_radius(slots, distance, pin_d) > bore / 2 + 3, "the locking disc is too small for its axle: make the distance longer, the pin thinner or the bore smaller");
|
|
539
|
+
ro = geneva_wheel_radius(slots, distance, pin_d);
|
|
540
|
+
assert(distance - ro - clearance >= bore / 2 + 2, str("the wheel passes within ", round(10 * (distance - ro - clearance)) / 10, " mm of the driver's axle: use a bore of at most ", floor(20 * (distance - ro - clearance - 2)) / 10, " mm or fewer slots"));
|
|
541
|
+
difference() {
|
|
542
|
+
circle(r = geneva_lock_radius(slots, distance, pin_d));
|
|
543
|
+
// Everywhere the wheel's rim passes while the pin is in a slot
|
|
544
|
+
on = 90 - 180 / slots;
|
|
545
|
+
n = max(2, ceil(2 * on / 3));
|
|
546
|
+
for (i = [0:n - 1]) hull() for (t = [-on + 2 * on * i / n, -on + 2 * on * (i + 1) / n])
|
|
547
|
+
translate([distance * cos(t), distance * sin(t)]) circle(r = ro + clearance);
|
|
548
|
+
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// The crank above the locking disc that carries the pin, along +x
|
|
553
|
+
module geneva_crank(slots, distance, pin_d = 6, bore = 6, width = 0, square = false) {
|
|
554
|
+
rc = geneva_pin_radius(slots, distance);
|
|
555
|
+
w = width > 0 ? width : max(pin_d, bore) + 8;
|
|
556
|
+
difference() {
|
|
557
|
+
hull() {
|
|
558
|
+
circle(d = w);
|
|
559
|
+
translate([rc, 0]) circle(d = pin_d + 8);
|
|
560
|
+
}
|
|
561
|
+
translate([rc, 0]) circle(d = pin_d);
|
|
562
|
+
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// A ratchet wheel of \`teeth\` teeth, radius r at their tips, \`depth\` deep,
|
|
567
|
+
// centred on the origin with a hole for its axle. It turns anticlockwise
|
|
568
|
+
// freely; a pawl() stops it turning back.
|
|
569
|
+
module ratchet(teeth, r, depth, bore = 6, square = false) {
|
|
570
|
+
p = 360 / teeth;
|
|
571
|
+
difference() {
|
|
572
|
+
polygon([for (k = [0:teeth - 1], j = [0, 1])
|
|
573
|
+
j == 0 ? [r * cos(k * p), r * sin(k * p)]
|
|
574
|
+
: [(r - depth) * cos((k + 1) * p), (r - depth) * sin((k + 1) * p)]]);
|
|
575
|
+
if (square) rect([bore, bore], center = true); else circle(d = bore);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// The angle of the tooth face a pawl rests on, nearest \`at\` degrees
|
|
580
|
+
function pawl_face(teeth, at = 90) = round(at / (360 / teeth)) * 360 / teeth;
|
|
581
|
+
|
|
582
|
+
// How far the pawl leans out from the wheel's edge, in degrees: past the
|
|
583
|
+
// teeth's slope, so it clears them
|
|
584
|
+
function pawl_lean(teeth, r, depth) = atan(depth / ((r - depth / 2) * 2 * PI / teeth)) + 15;
|
|
585
|
+
|
|
586
|
+
// The shortest pawl of this width that clears the teeth: its tip edge,
|
|
587
|
+
// along the tooth face, must end before its far end does
|
|
588
|
+
function pawl_min_length(teeth, r, depth, width = 8) =
|
|
589
|
+
width * (0.5 + tan(pawl_lean(teeth, r, depth))) + 2;
|
|
590
|
+
|
|
591
|
+
// The pawl's outline round the wheel's centre: its tip on the root by the
|
|
592
|
+
// tooth face, its far end, and back along the face. Its pivot is the
|
|
593
|
+
// middle of its far end. A length of 0 picks 0.8 * r, or longer if the
|
|
594
|
+
// pawl must be to clear the teeth; pawl() refuses a length given shorter
|
|
595
|
+
// than pawl_min_length().
|
|
596
|
+
function pawl_points(teeth, r, depth, length = 0, width = 8, at = 90, clearance = 0.2) =
|
|
597
|
+
let (
|
|
598
|
+
f = pawl_face(teeth, at),
|
|
599
|
+
g = pawl_lean(teeth, r, depth),
|
|
600
|
+
shortest = pawl_min_length(teeth, r, depth, width),
|
|
601
|
+
L = length > 0 ? length : max(r * 0.8, shortest),
|
|
602
|
+
n = [cos(f), sin(f)],
|
|
603
|
+
tc = [sin(f), -cos(f)],
|
|
604
|
+
u = cos(g) * tc + sin(g) * n,
|
|
605
|
+
v = cos(g) * n - sin(g) * tc,
|
|
606
|
+
T = (r - depth + clearance) * n + clearance * tc
|
|
607
|
+
)
|
|
608
|
+
[T, T + (L - width / 2) * u, T + (L - width / 2) * u + width * v, T + width / cos(g) * n];
|
|
609
|
+
|
|
610
|
+
// Where a pawl()'s pivot is, round the wheel's centre
|
|
611
|
+
function pawl_pivot(teeth, r, depth, length = 0, width = 8, at = 90, clearance = 0.2) =
|
|
612
|
+
let (p = pawl_points(teeth, r, depth, length, width, at, clearance)) (p[1] + p[2]) / 2;
|
|
613
|
+
|
|
614
|
+
// A pawl for a ratchet() of the same sizes, drawn where it works round
|
|
615
|
+
// the wheel's centre: give it the wheel's placement. Its tip rests against
|
|
616
|
+
// the tooth face nearest \`at\` degrees, and it turns on a pin through the
|
|
617
|
+
// hole at pawl_pivot(). Gravity, a rubber band or a spring wire holds it
|
|
618
|
+
// down on the teeth.
|
|
619
|
+
module pawl(teeth, r, depth, length = 0, width = 8, bore = 3, at = 90, clearance = 0.2) {
|
|
620
|
+
shortest = pawl_min_length(teeth, r, depth, width);
|
|
621
|
+
assert(length == 0 || length >= shortest, str("a pawl ", width, " mm wide must be at least ", ceil(2 * shortest) / 2, " mm long to clear the teeth: make it longer or narrower"));
|
|
622
|
+
p = pawl_points(teeth, r, depth, length, width, at, clearance);
|
|
623
|
+
H = (p[1] + p[2]) / 2;
|
|
624
|
+
difference() {
|
|
625
|
+
union() {
|
|
626
|
+
polygon(p);
|
|
627
|
+
translate(H) circle(d = width);
|
|
628
|
+
}
|
|
629
|
+
translate(H) circle(d = bore);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
373
632
|
`,"kerf/geo":`// kerf/geo: the world's land, for maps, globes and country-shaped pieces.
|
|
374
633
|
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
375
634
|
// The land data is Natural Earth's 1:110m land (public domain,
|
|
@@ -1000,6 +1259,60 @@ module halved_pair(name, at = [0, 0, 0], cap = undef, feet = [], side_feet = und
|
|
|
1000
1259
|
}
|
|
1001
1260
|
}
|
|
1002
1261
|
}
|
|
1262
|
+
`,"kerf/linkage":`// kerf/linkage: where the joints of a linkage are at a crank angle.
|
|
1263
|
+
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
1264
|
+
//
|
|
1265
|
+
// Each function gives the joint points of a linkage drawn flat, so a part
|
|
1266
|
+
// placed on a link and the link's length come from the same numbers. Use
|
|
1267
|
+
// them to place moving parts at a drive angle, and to check a linkage closes
|
|
1268
|
+
// over a whole turn.
|
|
1269
|
+
|
|
1270
|
+
// Where a circle of radius ra round a meets one of radius rb round b: the
|
|
1271
|
+
// point left of the line from a to b (side = 1) or right of it (side = -1).
|
|
1272
|
+
// undef when the circles don't meet: the links are too short or too long.
|
|
1273
|
+
function circle_meet(a, ra, b, rb, side = 1) =
|
|
1274
|
+
let (
|
|
1275
|
+
dx = b[0] - a[0],
|
|
1276
|
+
dy = b[1] - a[1],
|
|
1277
|
+
d = sqrt(dx * dx + dy * dy),
|
|
1278
|
+
along = d > 0 ? (ra * ra - rb * rb + d * d) / (2 * d) : 0,
|
|
1279
|
+
h2 = ra * ra - along * along
|
|
1280
|
+
)
|
|
1281
|
+
d == 0 || h2 < -1e-9 ? undef
|
|
1282
|
+
: let (h = sqrt(max(0, h2)), ux = dx / d, uy = dy / d)
|
|
1283
|
+
[a[0] + along * ux - side * h * uy, a[1] + along * uy + side * h * ux];
|
|
1284
|
+
|
|
1285
|
+
// A crank of radius r turning round the origin drives a slider along the
|
|
1286
|
+
// line y = offset through a connecting rod of length l. At the crank's
|
|
1287
|
+
// angle it gives [crank pin, slider pin]; undef if the rod can't reach.
|
|
1288
|
+
function slider_crank(r, l, angle, offset = 0) =
|
|
1289
|
+
let (
|
|
1290
|
+
pin = [r * cos(angle), r * sin(angle)],
|
|
1291
|
+
dy = offset - pin[1]
|
|
1292
|
+
)
|
|
1293
|
+
abs(dy) > l ? undef : [pin, [pin[0] + sqrt(l * l - dy * dy), offset]];
|
|
1294
|
+
|
|
1295
|
+
// How far the slider of slider_crank() travels from end to end
|
|
1296
|
+
function slider_stroke(r, l, offset = 0) =
|
|
1297
|
+
sqrt(pow(l + r, 2) - offset * offset) - sqrt(pow(l - r, 2) - offset * offset);
|
|
1298
|
+
|
|
1299
|
+
// A four-bar linkage: the crank turns round the origin, the rocker round
|
|
1300
|
+
// [ground, 0], and the coupler joins their ends. At the crank's angle it
|
|
1301
|
+
// gives [crank end, rocker end], the rocker end on the side \`side\` of the
|
|
1302
|
+
// line from the crank end to the rocker's pivot; undef where the links
|
|
1303
|
+
// can't close.
|
|
1304
|
+
function four_bar(ground, crank, coupler, rocker, angle, side = 1) =
|
|
1305
|
+
let (b = [crank * cos(angle), crank * sin(angle)], c = circle_meet(b, coupler, [ground, 0], rocker, side))
|
|
1306
|
+
is_undef(c) ? undef : [b, c];
|
|
1307
|
+
|
|
1308
|
+
// True when the crank of a four-bar linkage turns all the way round
|
|
1309
|
+
// (Grashof's rule, with the crank the shortest link)
|
|
1310
|
+
function four_bar_turns(ground, crank, coupler, rocker) =
|
|
1311
|
+
let (s = min(ground, crank, coupler, rocker), l = max(ground, crank, coupler, rocker))
|
|
1312
|
+
crank == s && s + l <= ground + crank + coupler + rocker - s - l;
|
|
1313
|
+
|
|
1314
|
+
// The angle in degrees of the line from a to b, from +x
|
|
1315
|
+
function link_angle(a, b) = atan2(b[1] - a[1], b[0] - a[0]);
|
|
1003
1316
|
`,"kerf/lock":`// kerf/lock: a lock with a key, for boxes, diaries, chests and money boxes.
|
|
1004
1317
|
// Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
|
|
1005
1318
|
//
|
|
@@ -1184,11 +1497,20 @@ function card_size(name) = let (s = lookup_size(name, CARD_SIZES))
|
|
|
1184
1497
|
is_undef(s) ? assert(false, str("Unknown card size \\"", name, "\\". Known: ", size_names(CARD_SIZES))) : s;
|
|
1185
1498
|
|
|
1186
1499
|
// Photo print sizes as [width, height], landscape: "4x6", "5x7", "8x10",
|
|
1187
|
-
// "10x15" (cm), "13x18" (cm),
|
|
1188
|
-
// "
|
|
1189
|
-
function photo_size(name) = let (s = lookup_size(name, PHOTO_SIZES))
|
|
1500
|
+
// "10x15" (cm), "13x18" (cm), and instant film: "instant mini", "instant
|
|
1501
|
+
// square", "instant wide" and "instant classic".
|
|
1502
|
+
function photo_size(name) = let (s = lookup_size(lookup_alias(name, PHOTO_ALIASES), PHOTO_SIZES))
|
|
1190
1503
|
is_undef(s) ? assert(false, str("Unknown photo size \\"", name, "\\". Known: ", size_names(PHOTO_SIZES))) : s;
|
|
1191
1504
|
|
|
1505
|
+
// A bought part's sizes by name, as a record: \`body\` [width, depth,
|
|
1506
|
+
// height], and for parts with one, the \`shaft\` diameter, the \`shaft_length\`
|
|
1507
|
+
// it stands out of the body and the \`hole\` to cut for it. Retail sizes vary:
|
|
1508
|
+
// measure yours. "music-18" (an 18-note wind-up music box movement, shaft
|
|
1509
|
+
// the winding key's), "quartz-clock" (a 56 mm quartz clock movement with
|
|
1510
|
+
// the 16.5 mm shaft for dials up to 8 mm thick), "marble-16" and "marble-25".
|
|
1511
|
+
function part_size(name) = let (s = lookup_size(name, PART_SIZES))
|
|
1512
|
+
is_undef(s) ? assert(false, str("Unknown part \\"", name, "\\". Known: ", size_names(PART_SIZES))) : s;
|
|
1513
|
+
|
|
1192
1514
|
// A size turned to lie wider than tall
|
|
1193
1515
|
function landscape(size) = size[0] >= size[1] ? size : [size[1], size[0]];
|
|
1194
1516
|
// A size turned to stand taller than wide
|
|
@@ -1210,13 +1532,28 @@ CARD_SIZES = [
|
|
|
1210
1532
|
];
|
|
1211
1533
|
PHOTO_SIZES = [
|
|
1212
1534
|
["4x6", [152.4, 101.6]], ["5x7", [177.8, 127]], ["8x10", [254, 203.2]],
|
|
1213
|
-
["10x15", [150, 100]], ["13x18", [180, 130]], ["
|
|
1214
|
-
["
|
|
1535
|
+
["10x15", [150, 100]], ["13x18", [180, 130]], ["instant mini", [54, 86]],
|
|
1536
|
+
["instant square", [72, 86]], ["instant wide", [108, 86]], ["instant classic", [88, 107]]
|
|
1537
|
+
];
|
|
1538
|
+
// Older names that still work, left out of the list of known names
|
|
1539
|
+
PHOTO_ALIASES = [
|
|
1540
|
+
["instax mini", "instant mini"], ["instax square", "instant square"],
|
|
1541
|
+
["instax wide", "instant wide"], ["polaroid", "instant classic"]
|
|
1542
|
+
];
|
|
1543
|
+
PART_SIZES = [
|
|
1544
|
+
["music-18", {body = [50, 44, 20], shaft = 3.5, hole = 6}],
|
|
1545
|
+
["quartz-clock", {body = [56, 56, 16], shaft = 7.6, shaft_length = 16.5, hole = 8, dial = 8}],
|
|
1546
|
+
["marble-16", {body = [16, 16, 16]}],
|
|
1547
|
+
["marble-25", {body = [25, 25, 25]}]
|
|
1215
1548
|
];
|
|
1216
1549
|
|
|
1217
1550
|
// The size of that name in a table of [name, size], ignoring case
|
|
1218
1551
|
function lookup_size(name, table) = let (k = lower(name), hit = [for (e = table) if (lower(e[0]) == k) e[1]])
|
|
1219
1552
|
len(hit) ? hit[0] : undef;
|
|
1553
|
+
// The name an older name stands for in a table of [old, new], or the name
|
|
1554
|
+
// itself
|
|
1555
|
+
function lookup_alias(name, aliases) = let (k = lower(name), hit = [for (e = aliases) if (lower(e[0]) == k) e[1]])
|
|
1556
|
+
len(hit) ? hit[0] : name;
|
|
1220
1557
|
// The names in a table, for messages
|
|
1221
1558
|
function size_names(table) = join([for (e = table) e[0]], ", ");
|
|
1222
1559
|
`,"kerf/symbols":`// kerf/symbols: 867 pictograms by name, for engraving and cutting.
|
|
@@ -2219,10 +2556,10 @@ module tab_rect(size, edges = true, count = undef, width = undef) {
|
|
|
2219
2556
|
if (e[2]) translate([w, h]) rotate(180) tabs(w, count, width);
|
|
2220
2557
|
if (e[3]) translate([0, h]) rotate(270) tabs(h, count, width);
|
|
2221
2558
|
}
|
|
2222
|
-
`};var P="0.3";var u="kerf.json",
|
|
2223
|
-
`));c.update(`${l}\0${e.length}\0`),c.update(e)}return"sha256-"+c.digest("base64")}function h1(a){return a.kind==="folder"?"folder:"+(process.platform==="win32"?a.path.toLowerCase():a.path):a.kind==="github"?`github:${a.owner}/${a.repo}`.toLowerCase()+`@${a.ref}`:a.url}function Z(a,c){let l=/^github:([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@(\S+))?$/.exec(a);if(l)return{kind:"github",owner:l[1],repo:l[2],ref:l[3]??"HEAD"};if(/^https?:\/\//i.test(a)){let n;try{n=new URL(a)}catch{return
|
|
2224
|
-
`};async function M1(a,c={}){let l=c.fetch??globalThis.fetch,e=c.log??(()=>{}),n=c.cache??new Map,t=
|
|
2225
|
-
`)&&
|
|
2226
|
-
`)&&(0,
|
|
2227
|
-
`);try{return await M1(a,l)}catch(h){throw n===void 0?(0,
|
|
2228
|
-
`));let i=[...t.keys()].sort().map(M=>[`${e}/${M}`,t.get(M)]),o=c??(0,m.join)(a,`${e}-${n}.tar.gz`);return(0,
|
|
2559
|
+
`};var P="0.3";var u="kerf.json",H="kerf.lock",A="kerf_libraries",_=20<<20,I=2e3,W=/^[a-z0-9][a-z0-9_-]{0,63}$/,A1=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,y1=/^(readme|licen[cs]e|copying|notice|changelog)(\.[a-z]+)?$/i,R=class extends Error{},U=a=>{try{return(0,z.statSync)(a).isFile()}catch{return!1}},V=a=>{try{return(0,z.statSync)(a).isDirectory()}catch{return!1}},S=(a,c)=>a&&Object.prototype.hasOwnProperty.call(a,c)?a[c]:void 0,d=a=>{throw new R(a)};function s1(a,c){return(typeof a!="string"||!W.test(a))&&d(`${c} "${a}" is not a library name: use lowercase letters, digits, - and _`),a==="kerf"&&d(`${c}: "kerf" is the standard library's name`),a}function Q(a,c){(!a||typeof a!="object"||Array.isArray(a))&&d(`${c} must hold a JSON object`);let l=a;for(let n of["name","version","description","license","language"])l[n]!==void 0&&typeof l[n]!="string"&&d(`${c}: "${n}" must be a string`);l.name!==void 0&&s1(l.name,`${c}: name`),l.version!==void 0&&!A1.test(l.version)&&d(`${c}: "version" must look like 1.2.0, not "${l.version}"`),l.language!==void 0&&!/^\d+\.\d+$/.test(l.language)&&d(`${c}: "language" must look like ${P}, not "${l.language}"`),l.sheet!==void 0&&!(Array.isArray(l.sheet)&&l.sheet.length===2&&l.sheet.every(n=>typeof n=="number"&&Number.isFinite(n)&&n>0))&&d(`${c}: "sheet" must be [width, height] in mm, like [600, 400]`);let e=l.libraries??{};(!e||typeof e!="object"||Array.isArray(e))&&d(`${c}: "libraries" must be an object of name: source`);for(let[n,t]of Object.entries(e))s1(n,`${c}: library`),typeof t!="string"&&d(`${c}: the source of ${n} must be a string`);return{...l,libraries:{...e}}}function J(a,c){let l;try{l=(0,z.readFileSync)(a,"utf8")}catch{return d(`${c} was not found`)}try{return JSON.parse(l)}catch(e){return d(`${c} is not valid JSON: ${e.message}`)}}function k(a,c=u){return Q(J((0,m.join)(a,u),c),c)}function Y(a){if(!(0,z.existsSync)((0,m.join)(a,H)))return;let c=J((0,m.join)(a,H),H);(c?.lockVersion!==1||!c.libraries||typeof c.libraries!="object")&&d(`${H} is not a kerf.lock this kerf can read. Delete it and run kerf install.`);for(let[l,e]of Object.entries(c.libraries))(!e||["source","resolved","integrity"].some(n=>typeof e[n]!="string"))&&d(`${H}: the entry for ${l} is damaged. Remove it and run kerf install.`);return c}function X(a){for(let c=(0,m.resolve)(a);;){if(U((0,m.join)(c,u)))return c;let l=(0,m.dirname)(c);if(l===c)return;c=l}}function c1(a){try{return k(a).name}catch{return}}function o1(a,c,l=U){let e=(h,s)=>[(0,m.join)(h,s),(0,m.join)(h,s+".kerf")].find(i=>l(i));if((0,m.isAbsolute)(c))return[c,c+".kerf"].find(h=>l(h));let n=c.indexOf("/"),t=n>0?X(a):void 0;if(t){let h=c.slice(0,n);if(h===c1(t))return e(t,c.slice(n+1));if(V((0,m.join)(t,A,h)))return e((0,m.join)(t,A),c)}return e(a,c)}function C1(a){let c=(0,m.dirname)((0,m.resolve)(a));return l=>{let e=o1(c,l);return e===void 0?void 0:(0,z.readFileSync)(e,"utf8")}}function H1(a,c=200){let l=X(a);if(!l)return[];let e=[],n=(s,i)=>{for(let o of[...v1(s,3)].sort()){if(e.length>=c)return;o.endsWith(".kerf")&&e.push(i+o.slice(0,-5))}},t=c1(l);t&&n(l,t+"/");let h=(0,m.join)(l,A);if(V(h))for(let s of(0,z.readdirSync)(h).sort())W.test(s)&&V((0,m.join)(h,s))&&n((0,m.join)(h,s),s+"/");return e}function v1(a,c=1/0){let l=[],e=(n,t,h)=>{let s;try{s=(0,z.readdirSync)(n,{withFileTypes:!0})}catch{return}for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||i.name===A)continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?h<c&&e((0,m.join)(n,i.name),o,h+1):i.isFile()&&(l.push(o),l.length>I&&d(`${a} has more than ${I} files`))}};return e(a,"",0),l}function O(a,c=()=>!0){let l=new Map;for(let e of v1(a))c(e)&&l.set(e,(0,z.readFileSync)((0,m.join)(a,...e.split("/"))));return l}var l1=a=>a===u||a.endsWith(".kerf")||!a.includes("/")&&y1.test(a);function T(a){let c=(0,r1.createHash)("sha256");for(let l of[...a.keys()].sort()){let e=Buffer.from(a.get(l).toString("utf8").replace(/\r\n/g,`
|
|
2560
|
+
`));c.update(`${l}\0${e.length}\0`),c.update(e)}return"sha256-"+c.digest("base64")}function h1(a){return a.kind==="folder"?"folder:"+(process.platform==="win32"?a.path.toLowerCase():a.path):a.kind==="github"?`github:${a.owner}/${a.repo}`.toLowerCase()+`@${a.ref}`:a.url}function Z(a,c){let l=/^github:([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@(\S+))?$/.exec(a);if(l)return{kind:"github",owner:l[1],repo:l[2],ref:l[3]??"HEAD"};if(/^https?:\/\//i.test(a)){let n;try{n=new URL(a)}catch{return d(`${a} is not a link`)}return n.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(n.hostname)&&d(`Use https:// to download ${a}`),{kind:"url",url:a}}let e=a.startsWith("file:")?a.slice(5):a;return e.startsWith("./")||e.startsWith("../")||(0,m.isAbsolute)(e)?{kind:"folder",path:(0,m.resolve)(c,e)}:d(`"${a}" is not a library source. Use github:owner/repo@tag, an https:// link to a .tar.gz, or a folder like ./my-library`)}async function k1(a,c){let l;try{l=await c(a)}catch(s){let i=s;return d(`Could not download ${a}: ${i.cause?.message??i.message}`)}l.ok||d(`Could not download ${a}: HTTP ${l.status}`+(l.status===404?". Check the name and the tag, and that it is public.":""));let e=()=>d(`${a} is larger than ${_>>20} MB`);if(Number(l.headers?.get("content-length"))>_&&e(),!l.body){let s=Buffer.from(await l.arrayBuffer());return s.length>_?e():s}let n=l.body.getReader(),t=[],h=0;for(;;){let{done:s,value:i}=await n.read();if(s||!i)break;h+=i.length,h>_&&(await n.cancel().catch(()=>{}),e()),t.push(i)}return Buffer.concat(t)}function V1(a,c){let l;try{l=(0,E.gunzipSync)(a,{maxOutputLength:5*_})}catch{return d(`${c} is not a .tar.gz file`)}let e=new Map,n,t={},h;for(let s=0;s+512<=l.length;){let i=l.subarray(s,s+512);if(i.every(b=>b===0))break;let o=(b,y)=>{let L=i.subarray(b,b+y),q=L.indexOf(0);return L.subarray(0,q<0?y:q).toString("utf8")},M=parseInt(o(124,12).trim()||"0",8);M>=0||d(`${c} is damaged`);let f=o(156,1)||"0",r=l.subarray(s+512,s+512+M);if(s+=512+Math.ceil(M/512)*512,f==="x"||f==="g"){let b=q1(r);f==="g"?n=b.comment??n:t=b;continue}if(f==="L"){h=r.toString("utf8").replace(/\0+$/,"");continue}let v=o(345,155),g=t.path??h??(v?v+"/":"")+o(0,100);t={},h=void 0,(f==="0"||f==="7")&&e.set(g,Buffer.from(r)),e.size>I&&d(`${c} has more than ${I} files`)}return{files:e,commit:n}}function q1(a){let c={};for(let l=0;l<a.length;){let e=a.indexOf(32,l),n=parseInt(a.subarray(l,e).toString(),10);if(!(n>0)||e<0)break;let t=a.subarray(e+1,l+n-1).toString("utf8"),h=t.indexOf("=");h>0&&(c[t.slice(0,h)]=t.slice(h+1)),l+=n}return c}function i1(a,c){let l=new Map;for(let[t,h]of a){let s=t.replace(/^\.\//,""),i=s.split("/");((0,m.isAbsolute)(s)||s.includes("\\")||s.includes(":")||i.some(o=>o===".."||o===""))&&d(`${c} holds a file outside its folder: ${t}`),l.set(s,h)}let e="";if(!l.has(u)){let t=new Set([...l.keys()].map(h=>h.split("/")[0]));t.size===1&&(e=[...t][0]+"/")}let n=new Map;for(let[t,h]of l){if(!t.startsWith(e))continue;let s=t.slice(e.length);s.split("/").some(i=>i.startsWith(".")||i===A||i==="node_modules")||l1(s)&&n.set(s,h)}return n.has(u)||d(`${c} has no kerf.json at its top. Is it a KerfScript library?`),n}var x1=(a,c)=>{let[l,e]=a.split(".").map(Number),[n,t]=c.split(".").map(Number);return l>n||l===n&&e>t};async function m1(a,c,l,e,n){let t=Z(a,c),h,s;if(t.kind==="folder")U((0,m.join)(t.path,u))||d(`${a}: no kerf.json in ${t.path}. Is it a KerfScript library?`),h=i1(O(t.path,l1),a),s=(0,m.relative)(l,t.path).split(m.sep).join("/")||".",!s.startsWith(".")&&!(0,m.isAbsolute)(s)&&(s="./"+s);else{let o=t.kind==="github"?`https://github.com/${t.owner}/${t.repo}/archive/${t.ref}.tar.gz`:t.url,M=n.get(o)??await k1(o,e);n.set(o,M);let f=V1(M,a);h=i1(f.files,a),s=t.kind==="github"&&/^[0-9a-f]{40}$/.test(f.commit??"")?`https://github.com/${t.owner}/${t.repo}/archive/${f.commit}.tar.gz`:o}let i=Q(JSON.parse(h.get(u).toString("utf8")),`the kerf.json of ${a}`);return i.name||d(`${a}: its kerf.json has no "name", so it is not a library`),i.language&&x1(i.language,P)&&d(`${i.name} needs KerfScript language ${i.language} or later, and this kerf has ${P}. Update kerf.`),{manifest:i,files:h,resolved:s,integrity:T(h)}}function _1(a,c){(0,z.rmSync)(a,{recursive:!0,force:!0});for(let[l,e]of c){let n=(0,m.join)(a,...l.split("/"));(0,z.mkdirSync)((0,m.dirname)(n),{recursive:!0}),(0,z.writeFileSync)(n,e)}}var S1=a=>{let c=[...a].sort(([l],[e])=>l<e?-1:1);return JSON.stringify({lockVersion:1,libraries:Object.fromEntries(c)},null,2)+`
|
|
2561
|
+
`};async function M1(a,c={}){let l=c.fetch??globalThis.fetch,e=c.log??(()=>{}),n=c.cache??new Map,t=k(a),h=Y(a),s=new Map,i=Object.entries(t.libraries).map(([r,v])=>({name:r,source:v,base:a,from:u})),o=(0,m.join)(a,A);for(;i.length;){let{name:r,source:v,base:g,from:b}=i.shift(),y=Z(v,g),L=y.kind==="folder",q=L?`${v} (${y.path})`:v,j=s.get(r);if(j){j.at!==h1(y)&&!S(t.libraries,r)&&d(`${b} uses ${r} from ${q}, and ${j.from} uses it from ${j.shown}. Add ${r} to kerf.json with the source to use.`);continue}let G=S(h?.libraries,r),w=G?.source===v&&(!L||(0,m.resolve)(a,G.resolved)===y.path)?G:void 0;c.frozen&&!w&&d(`kerf.lock does not pin ${r} from ${v}. Run kerf install without --frozen.`);let $=(0,m.join)(o,r),x;if(w&&!L&&V($)&&T(O($))===w.integrity)x=w;else{let p=await m1(w&&!L?w.resolved:v,L?g:a,a,l,n);p.manifest.name!==r&&d(`${v} is the library "${p.manifest.name}", so ${b} must call it ${p.manifest.name}, not ${r}`),w&&p.integrity!==w.integrity&&(!L||c.frozen)&&d(L?`${r} in ${v} changed since kerf.lock pinned it. Run kerf install without --frozen.`:`${r} from ${w.resolved} no longer matches kerf.lock. If you trust the change, remove ${r} from kerf.lock and run kerf install again.`),_1($,p.files),x={source:v,...p.manifest.version?{version:p.manifest.version}:{},resolved:p.resolved,integrity:p.integrity},(!w||w.integrity!==p.integrity||!L)&&e(`${w?"Restored":"Installed"} ${r}${x.version?" "+x.version:""} from ${v}`)}s.set(r,{entry:x,at:h1(y),shown:q,from:b});let a1=y.kind==="folder"?y.path:void 0;for(let[p,F]of Object.entries(k($,`${A}/${r}/${u}`).libraries))Z(F,a).kind==="folder"&&!a1&&d(`${r} uses ${p} from the folder ${F}: a published library needs github: or https: sources`),i.push({name:p,source:F,base:a1??a,from:r})}let M=S1(new Map([...s].map(([r,v])=>[r,v.entry]))),f=(0,z.existsSync)((0,m.join)(a,H))?(0,z.readFileSync)((0,m.join)(a,H),"utf8"):"";if(c.frozen&&M!==f.replace(/\r\n/g,`
|
|
2562
|
+
`)&&d("kerf.lock is out of date. Run kerf install without --frozen."),V(o))for(let r of(0,z.readdirSync)(o,{withFileTypes:!0}))r.isDirectory()&&W.test(r.name)&&!s.has(r.name)&&((0,z.rmSync)((0,m.join)(o,r.name),{recursive:!0,force:!0}),e(`Removed ${r.name}`));return M!==f.replace(/\r\n/g,`
|
|
2563
|
+
`)&&(0,z.writeFileSync)((0,m.join)(a,H),M),JSON.parse(M)}function T1(a){let c=k(a),l=Y(a),e=Object.keys(c.libraries);if(!l)return e.length?["kerf.lock is missing. Run kerf install."]:[];let n=[],t=new Set,h=[...e];for(;h.length;){let s=h.shift();if(t.has(s))continue;t.add(s);let i=S(l.libraries,s);if(!i){n.push(`${s} is not in kerf.lock. Run kerf install.`);continue}e.includes(s)&&i.source!==c.libraries[s]&&n.push(`kerf.json takes ${s} from ${c.libraries[s]}, and kerf.lock from ${i.source}. Run kerf install.`);let o=(0,m.join)(a,A,s);if(!V(o)){n.push(`${s} is not in ${A}. Run kerf install.`);continue}T(O(o))!==i.integrity&&n.push(`The files in ${A}/${s} differ from kerf.lock. Run kerf install.`);try{h.push(...Object.keys(k(o).libraries))}catch(M){n.push(M.message)}}for(let s of Object.keys(l.libraries))t.has(s)||n.push(`kerf.lock pins ${s}, which nothing uses any more.`);return n}function j1(a,c){let l=(0,m.join)(a,u),e=(0,z.existsSync)(l)?J(l,u):{};Q(e,u);let n={...e.libraries??{}};return c(n),e.libraries=n,{file:l,before:(0,z.existsSync)(l)?(0,z.readFileSync)(l,"utf8"):void 0,raw:e}}async function d1(a,c,l){let{file:e,before:n,raw:t}=j1(a,c);(0,z.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
2564
|
+
`);try{return await M1(a,l)}catch(h){throw n===void 0?(0,z.rmSync)(e,{force:!0}):(0,z.writeFileSync)(e,n),h}}async function $1(a,c,l={}){let e=new Map,t=(await m1(c,a,a,l.fetch??globalThis.fetch,e)).manifest.name;t===c1(a)&&d(`This project is the library ${t}; it cannot use itself`);let h=await d1(a,s=>void(s[t]=c),{...l,cache:e});return{name:t,lock:h}}async function P1(a,c,l={}){return d1(a,e=>{S(e,c)===void 0&&d(`kerf.json has no library named ${c}`),delete e[c]},l)}function N(a,c=[]){if(Array.isArray(a))for(let l of a)N(l,c);else if(a&&typeof a=="object"){let l=a;if(l.kind==="use"&&typeof l.path=="string")c.push({path:l.path,line:l.pos.line});else for(let e of Object.values(l))N(e,c)}return c}function I1(a){let c=[];for(let[l,e]of a){let n=Buffer.alloc(512),t=l,h="";if(Buffer.byteLength(t)>100){let i=l.lastIndexOf("/",155);(i<0||Buffer.byteLength(l.slice(i+1))>100)&&d(`${l}: the path is too long to pack`),h=l.slice(0,i),t=l.slice(i+1)}n.write(t,0,100),n.write("0000644\0",100),n.write("0000000\0",108),n.write("0000000\0",116),n.write(e.length.toString(8).padStart(11,"0")+"\0",124),n.write("00000000000\0",136),n.fill(32,148,156),n.write("0",156),n.write("ustar\0",257),n.write("00",263),n.write(h,345,155);let s=0;for(let i of n)s+=i;n.write(s.toString(8).padStart(6,"0")+"\0 ",148),c.push(n,e,Buffer.alloc((512-e.length%512)%512))}return c.push(Buffer.alloc(1024)),(0,E.gzipSync)(Buffer.concat(c),{level:9})}function R1(a,c){let l=k(a),e=l.name??d('kerf.json needs a "name" to pack a library'),n=l.version??d('kerf.json needs a "version", like 1.0.0'),t=O(a,l1),h=[];for(let[M,f]of Object.entries(l.libraries))Z(f,a).kind==="folder"&&h.push(`kerf.json: ${M} comes from a folder; a published library needs github: or https: sources`);let s=M=>t.has(M)||t.has(M+".kerf");for(let[M,f]of t){if(!M.endsWith(".kerf"))continue;let r;try{r=e1(f.toString("utf8"),`${e}/${M}`).program}catch(v){h.push(`${M}: ${v.message}`);continue}for(let v of N(r)){let g=v.path.split("/")[0];Object.prototype.hasOwnProperty.call(t1,v.path)||g===e&&s(v.path.slice(e.length+1))||v.path.includes("/")&&S(l.libraries,g)!==void 0||h.push(`${M}, line ${v.line}: <${v.path}> will not be found once the library is installed`+(s(v.path)?`. Write <${e}/${v.path}> for the library's own file.`:"."))}}[...t.keys()].some(M=>M.endsWith(".kerf"))||h.push("There are no .kerf files to pack"),h.length&&d(h.join(`
|
|
2565
|
+
`));let i=[...t.keys()].sort().map(M=>[`${e}/${M}`,t.get(M)]),o=c??(0,m.join)(a,`${e}-${n}.tar.gz`);return(0,z.writeFileSync)(o,I1(i)),{file:o,name:e,version:n,files:t.size,integrity:T(t)}}0&&(module.exports={FOLDER,LOCK,LibraryError,MANIFEST,add,check,findProject,install,installedPaths,integrity,libraryFile,pack,readLock,readManifest,remove,resolver});
|