@xlinklight/publishing 3.0.0 → 3.1.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/README.md CHANGED
@@ -6,7 +6,13 @@ Solution publishing binds declarative metadata, an opaque Worker module closure
6
6
 
7
7
  `prepareSolutionPackage` captures an explicit file/response-policy plan with declared path case semantics and file, byte and time limits. It rejects links, escapes, missing/extra files, collisions and changing bytes. `prepareSolutionPackageBytes` composes already captured snapshots without another filesystem staging tree. Both preserve binary bytes, BOMs, line endings and response headers. Their snapshots expose bounded `readFile(path, {maximumBytes, signal})` and `streamFile(path, {signal})`; the Node snapshot also retains its owned file bytes for local freezing. These results establish byte identity, not provider deployment or business acceptance.
8
8
 
9
- The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs only a pinned project configuration and token. `check` invokes the owner-installed `deployment/publishing.mjs` producer once per durable preparation; its `prepare` result must confirm `processesClosed: true`. Unknown producer closure requires recovery rather than another build. The default private client state is `state/solution-publishing`, separate from disposable build outputs. The caller owns filesystem access controls and backup policy for this secret-bearing journal.
9
+ The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs a pinned project configuration and token. A fresh `check` or `publish` selects an owner-installed producer in this order.
10
+
11
+ 1. An explicit `--producer` portable checkout-relative `.mjs` path.
12
+ 2. The checkout's `package.json` field `linkLight.publishingProducer`. Use a portable checkout-relative `.mjs` string or an object with a single `module` key naming a bare public package subpath, such as `{"module":"@example/owner-tools/deployment-producer"}`. Declare the package in the checkout's `dependencies` or `devDependencies` and install it under the checkout's `node_modules`. Node's `createRequire(...).resolve()` must find the export as a regular `.mjs` file within that installed package. The package can expose its ESM entry through the `default` condition. pnpm links to packages inside the checkout's `node_modules` are supported.
13
+ 3. `deployment/publishing.mjs` when the metadata field is absent.
14
+
15
+ The checkout manifest, installed producer's package manifest and producer entry each have a 64 KiB limit. Invalid selection fails closed before producer code runs. Correct the selection and use `--new-preparation` to retry a closed failure. Each durable preparation invokes the producer once and requires its `prepare` result to confirm `processesClosed: true`. Unknown producer closure requires recovery. Frozen requests retain their original bytes and can be resumed after the selection or its files change. The default private client state is `state/solution-publishing`, separate from disposable build outputs. The caller owns filesystem access controls and backup policy for this secret-bearing journal.
10
16
 
11
17
  The client never automatically repeats request creation. `publish` reuses frozen original bytes and an explicit request identity. CLI publish waits up to 300000 ms; `--no-wait` submits without waiting and `--wait-ms <1..3600000>` selects a finite wait. Programmatic `workflow.publish` defaults to one observation. Waiting uses GET only. Queued, pending or timed-out work exits 3; a closed failure exits 1; verified ACTIVE exits 0. Recovery observes the original operation without advancing its next stage. Resume may advance only after a known pending operation is observed successfully. Neither operation rebuilds, uploads or re-commits the package. Status and verification never dispatch work.
12
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xlinklight/publishing",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
package/src/node/cli.mjs CHANGED
@@ -9,6 +9,7 @@ import {parsePublishingConfiguration,protocolRecord,publishingError} from '../pr
9
9
  import {openPublishingJournal} from './journal.mjs';
10
10
  import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
11
11
  import {createPublishingWorkflow} from './workflow.mjs';
12
+ import {defaultProducer} from './source-producer.mjs';
12
13
 
13
14
  const commands=['credentials','check','publish','status','recover','verify','abandon'];
14
15
  const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
@@ -92,7 +93,7 @@ async function executeCommand(selected,options){
92
93
 
93
94
  export async function runPublishingCommand(args,options={}){
94
95
  let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
95
- if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:'deployment/publishing.mjs',stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
96
+ if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:defaultProducer,stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
96
97
  try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
97
98
  }
98
99
 
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {createRequire} from 'node:module';
4
+ import {validatePortableRelativePath} from '@openge/forge-path-safety';
5
+ import {protocolRecord,publishingError} from '../protocol.mjs';
6
+
7
+ export const defaultProducer='deployment/publishing.mjs';
8
+ const maximumSourceBytes=65536n;
9
+ const fail=code=>publishingError('SOURCE_'+code);
10
+ const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
11
+ const sameFile=(before,after)=>['dev','ino','size','mtimeNs','ctimeNs'].every(key=>before[key]===after[key]);
12
+ const readOnlyFlags=fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0);
13
+
14
+ export function validateLocalProducer(relative){
15
+ try{
16
+ if(validatePortableRelativePath(relative)===relative&&relative.endsWith('.mjs'))return relative;
17
+ }catch{
18
+ throw fail('PATH_INVALID');
19
+ }
20
+ throw fail('PATH_INVALID');
21
+ }
22
+
23
+ async function localProducerFile(root,relative){
24
+ const parts=relative.split('/');let current=root;
25
+ for(const [index,part] of parts.entries()){
26
+ current=path.join(current,part);const info=await fs.lstat(current,{bigint:true});
27
+ if(info.isSymbolicLink()||await fs.realpath(current)!==current||(index===parts.length-1?!info.isFile()||info.nlink!==1n||info.size>maximumSourceBytes:!info.isDirectory()))throw fail('PATH_INVALID');
28
+ }
29
+ return current;
30
+ }
31
+
32
+ async function readManifest(file,{checkout=false}={}){
33
+ let before;
34
+ try{before=await fs.lstat(file,{bigint:true});}
35
+ catch(error){if(checkout&&error.code==='ENOENT')return undefined;throw error;}
36
+ if(!before.isFile()||before.size>maximumSourceBytes||checkout&&before.nlink!==1n)throw fail('METADATA_INVALID');
37
+ const handle=await fs.open(file,readOnlyFlags);
38
+ try{
39
+ if(!sameFile(before,await handle.stat({bigint:true})))throw fail('METADATA_INVALID');
40
+ const bytes=Buffer.alloc(Number(before.size)+1);let offset=0;
41
+ while(offset<bytes.length){
42
+ const {bytesRead}=await handle.read(bytes,offset,bytes.length-offset,offset);
43
+ if(bytesRead===0)break;
44
+ offset+=bytesRead;
45
+ }
46
+ if(offset!==Number(before.size)||!sameFile(before,await handle.stat({bigint:true}))||!sameFile(before,await fs.lstat(file,{bigint:true})))throw fail('METADATA_INVALID');
47
+ const value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,offset)));
48
+ if(!record(value))throw fail('METADATA_INVALID');
49
+ return value;
50
+ }finally{await handle.close();}
51
+ }
52
+
53
+ function contains(parent,child){
54
+ const relative=path.relative(parent,child);
55
+ return relative!==''&&relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);
56
+ }
57
+
58
+ async function packageProducerFile(root,manifest,checkout,selection){
59
+ if(!protocolRecord(selection,['module'])||typeof selection.module!=='string'||selection.module.length>512)throw fail('METADATA_INVALID');
60
+ const specifier=selection.module;
61
+ const match=/^((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)(\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+$/.exec(specifier);
62
+ if(match?.[0]!==specifier)throw fail('METADATA_INVALID');
63
+ const packageName=match[1];
64
+ if(![checkout.dependencies,checkout.devDependencies].some(group=>record(group)&&Object.hasOwn(group,packageName)&&typeof group[packageName]==='string'&&group[packageName].trim()))throw fail('PACKAGE_UNDECLARED');
65
+
66
+ const modules=path.join(root,'node_modules');
67
+ if(await fs.realpath(modules)!==modules)throw fail('PATH_INVALID');
68
+ const installed=await fs.realpath(path.join(modules,...packageName.split('/')));
69
+ if(!contains(modules,installed))throw fail('PATH_INVALID');
70
+ const dependency=await readManifest(path.join(installed,'package.json'));
71
+ if(dependency.name!==packageName||dependency.exports==null)throw fail('PACKAGE_EXPORT_INVALID');
72
+ const file=await fs.realpath(createRequire(manifest).resolve(specifier));
73
+ if(!contains(installed,file)||!file.endsWith('.mjs'))throw fail('PATH_INVALID');
74
+ const info=await fs.lstat(file,{bigint:true});
75
+ if(!info.isFile()||info.size>maximumSourceBytes)throw fail('PATH_INVALID');
76
+ return file;
77
+ }
78
+
79
+ export async function selectProducerFile(root,explicit){
80
+ if(explicit!==undefined)return localProducerFile(root,explicit);
81
+ const manifest=path.join(root,'package.json'),checkout=await readManifest(manifest,{checkout:true});
82
+ const metadata=checkout?.linkLight;
83
+ if(metadata!==undefined&&!record(metadata))throw fail('METADATA_INVALID');
84
+ const selection=metadata?.publishingProducer;
85
+ if(selection===undefined)return localProducerFile(root,defaultProducer);
86
+ if(typeof selection==='string')return localProducerFile(root,validateLocalProducer(selection));
87
+ return packageProducerFile(root,manifest,checkout,selection);
88
+ }
@@ -3,26 +3,19 @@ import path from 'node:path';
3
3
  import {pathToFileURL} from 'node:url';
4
4
  import {randomUUID} from 'node:crypto';
5
5
  import {setTimeout as delay} from 'node:timers/promises';
6
- import {validatePortableRelativePath} from '@openge/forge-path-safety';
7
6
  import {createPublishingClient} from '../client.mjs';
8
7
  import {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
9
8
  import {createPublishingSession} from './session.mjs';
10
9
  import {verifyPublishingActivation} from './activation.mjs';
11
10
  import {PublishingSourceError} from './source-error.mjs';
11
+ import {selectProducerFile,validateLocalProducer} from './source-producer.mjs';
12
12
 
13
13
  const fail=code=>publishingError(code),sourceKey=id=>'source:'+id;
14
14
  const sourceOptions=input=>{
15
15
  if(!protocolRecord(input,[],['producer','newPreparation','signal'])||input.newPreparation!==undefined&&typeof input.newPreparation!=='boolean')throw fail('WORKFLOW_INPUT_INVALID');
16
- const producer=input.producer??'deployment/publishing.mjs';try{if(validatePortableRelativePath(producer)!==producer||!producer.endsWith('.mjs'))throw Error();}catch{throw fail('SOURCE_PATH_INVALID');}return {...input,producer};
16
+ if(input.producer!==undefined)validateLocalProducer(input.producer);
17
+ return input;
17
18
  };
18
- async function producerFile(root,relative){
19
- const selected=path.join(root,...relative.split('/'));let current=root;
20
- for(const [index,part]of relative.split('/').entries()){
21
- current=path.join(current,part);const info=await fs.lstat(current,{bigint:true});
22
- if(info.isSymbolicLink()||await fs.realpath(current)!==current||(index===relative.split('/').length-1? !info.isFile()||info.nlink!==1n||info.size>65536n:!info.isDirectory()))throw fail('SOURCE_PATH_INVALID');
23
- }
24
- return selected;
25
- }
26
19
 
27
20
  /** One active request per project/client journal. Recovery never imports source
28
21
  * or performs an operation whose durable Foundation claim already exists. */
@@ -71,12 +64,18 @@ export function createPublishingWorkflow(options){
71
64
  if(!newPreparation)throw fail('SOURCE_NEW_PREPARATION_REQUIRED');
72
65
  }
73
66
  signal?.throwIfAborted();if(await fs.realpath(root)!==root||!(await fs.lstat(root)).isDirectory())throw fail('SOURCE_PATH_INVALID');
74
- const project=await client(signal).getProject({signal}),requestId=randomUUID(),payload={schemaVersion:1,requestId,phase:'preparing',project,pathCaseSensitivity};
67
+ const project=await client(signal).getProject({signal}),requestId=randomUUID();
68
+ let file,selectionFailure;
69
+ try{file=await selectProducerFile(root,producer);}
70
+ catch(cause){selectionFailure=new PublishingSourceError({cause,processesClosed:true});}
71
+ signal?.throwIfAborted();
72
+ const payload={schemaVersion:1,requestId,project,pathCaseSensitivity,...(selectionFailure?{phase:'failed-closed',failure:{code:selectionFailure.code}}:{phase:'preparing'})};
75
73
  if(await journal.compareAndSet({key:sourceKey(requestId),expectedRevision:0,payload},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
76
74
  if(await journal.compareAndSet({key:activeKey,expectedRevision:previous?.active.revision??0,payload:{schemaVersion:1,requestId}},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
75
+ if(selectionFailure)throw selectionFailure;
77
76
  let record={revision:1,payload},prepared,intent,processesClosed=false;
78
77
  try{
79
- const file=await producerFile(root,producer),producerModule=await import(pathToFileURL(file).href+'?publishingRequest='+requestId);
78
+ const producerModule=await import(pathToFileURL(file).href+'?publishingRequest='+requestId);
80
79
  if(typeof producerModule.prepare!=='function')throw fail('SOURCE_PORT_INVALID');
81
80
  const response=await producerModule.prepare({root,project:structuredClone(project),signal,requestId});
82
81
  if(!protocolRecord(response,['prepared','processesClosed'])||response.processesClosed!==true)throw fail('SOURCE_PROCESS_CLOSURE_UNKNOWN');processesClosed=true;prepared=response.prepared;