create-pincast 0.1.0 → 0.2.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
@@ -10,7 +10,7 @@ You need Node 20.12 or later. The folder has to be new or empty. Leave its name
10
10
 
11
11
  ## What it does
12
12
 
13
- 1. Copies a small starter app, Lantern Walk, from inside this package. Nothing is downloaded from GitHub, and `template.json` records the commit it came from.
13
+ 1. Copies a small starter app, Lantern Walk. It comes inside `@pincast/cli`, the one package this one installs, so nothing is downloaded from GitHub. That package's `template.json` records the commit it came from.
14
14
  2. Asks Pincast for one test app.
15
15
  3. Writes your key to `.env`, which only your account can read and git ignores, along with the test person `test_demo` and your claim link.
16
16
  4. Puts the new app's id in `shared/app.js`.
@@ -35,17 +35,24 @@ If the set or the collect doesn't go through, you still get your app. The comman
35
35
 
36
36
  ## Working on this package
37
37
 
38
+ From 0.2.0 on, this package is a shim. The command's code, its starter app and its text are in `@pincast/cli`, and the `pincast init` command there runs the same code. This package gives it the name `npm create pincast`, and depends on one exact version of `@pincast/cli`.
39
+
38
40
  ```sh
41
+ npm install
39
42
  npm test
40
43
  ```
41
44
 
42
45
  The tests run against a local stand-in for the API and never reach Pincast. Set `PINCAST_CREATE_API` to point the command at another address.
43
46
 
44
- To move the starter to a newer commit of the example app:
47
+ To move the starter to a newer commit of the example app, sync it in `@pincast/cli` and release that, then move this package's pin to the new version. [RELEASING.md](RELEASING.md) has the steps, and [CHANGELOG.md](CHANGELOG.md) lists what each release changed.
45
48
 
46
- ```sh
47
- node scripts/sync-template.js <path to pincast-kit-example> <commit>
48
- ```
49
+ ## Versions
50
+
51
+ - **Patch** (0.2.0 to 0.2.1): a fix, or a change a script can't see, such as clearer text.
52
+ - **Minor** (0.2.1 to 0.3.0): something new, and everything that worked still works.
53
+ - **Major** (0.3.0 to 1.0.0): something that worked can stop working, such as an exit code that changes meaning or a higher lowest Node version.
54
+
55
+ A release that moves the `@pincast/cli` pin takes the larger of the two changes. While the version starts with 0, a range like `^0.2.0` takes patches only.
49
56
 
50
57
  ## License
51
58
 
package/package.json CHANGED
@@ -1,27 +1,38 @@
1
1
  {
2
2
  "name": "create-pincast",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "One command to a working Placecard app with its own test key.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/pincastFM/create-pincast.git"
9
9
  },
10
+ "homepage": "https://github.com/pincastFM/create-pincast#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/pincastFM/create-pincast/issues"
13
+ },
10
14
  "type": "module",
11
15
  "bin": {
12
16
  "create-pincast": "bin/create-pincast.js"
13
17
  },
14
18
  "files": [
15
19
  "bin",
16
- "src",
17
- "template",
18
- "template.json"
20
+ "src"
19
21
  ],
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org"
25
+ },
20
26
  "engines": {
21
27
  "node": ">=20.12"
22
28
  },
29
+ "dependencies": {
30
+ "@pincast/cli": "0.1.0"
31
+ },
23
32
  "scripts": {
24
- "test": "node --test test/*.test.js"
33
+ "test": "node --test test/*.test.js",
34
+ "link-cli": "node scripts/link-cli.mjs",
35
+ "changelog": "node scripts/changelog.mjs"
25
36
  },
26
37
  "keywords": [
27
38
  "pincast",
package/src/cli.js CHANGED
@@ -1,175 +1,7 @@
1
- import { mkdirSync, readdirSync, statSync } from 'node:fs'
2
- import { basename, isAbsolute, join, relative, resolve } from 'node:path'
3
- import { apiBase, makeTestApp, Stop } from './api.js'
4
- import { FIRST_RUN_TIMEOUT_MS, sendFirstRun } from './firstrun.js'
5
- import { COMMAND } from './name.js'
6
- import { addReadmeSection, copyStarter, firstRunCommands, removeStarter, setAppId, TEST_PERSON, writeEnv } from './starter.js'
7
-
8
- const DEFAULT_FOLDER = 'pincast-app'
9
-
10
- const USAGE = `Make a Placecard app with its own test key:
11
-
12
- ${COMMAND} [folder]
13
-
14
- The folder has to be new or empty. With no folder named, the app goes in ./${DEFAULT_FOLDER}.
15
- `
16
-
17
- // Every line this command prints passes through here, so a key can't reach the terminal even by mistake.
18
- const hideKeys = text => String(text).replace(/pck_[A-Za-z0-9_-]+/g, '[key hidden]')
19
-
20
- const shellWord = word => (/^[A-Za-z0-9._/-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`)
21
-
22
- /** Reads the arguments: at most one folder. */
23
- function parseArgs(argv) {
24
- const flags = argv.filter(a => a.startsWith('-'))
25
- if (flags.some(f => f === '-h' || f === '--help')) return { help: true }
26
- if (flags.length) throw new Stop(`This command takes no options.\n\n${USAGE}`, 2)
27
- if (argv.length > 1) throw new Stop(`This command takes one folder.\n\n${USAGE}`, 2)
28
- const folder = argv[0] ?? DEFAULT_FOLDER
29
- // eslint-disable-next-line no-control-regex
30
- if (!folder.trim() || /[\u0000-\u001f\u007f]/.test(folder)) throw new Stop("That folder name can't be used.", 2)
31
- return { folder }
32
- }
33
-
34
- /** Refuses anything but a new or empty folder, before any call is made. Answers whether it exists. */
35
- function checkTarget(target, shown) {
36
- let info
37
- try {
38
- info = statSync(target)
39
- } catch (e) {
40
- if (e.code === 'ENOENT') return false
41
- throw new Stop(`Couldn't read ${shown} (${e.code}).`)
42
- }
43
- if (!info.isDirectory()) throw new Stop(`${shown} is a file. Name a new or empty folder.`)
44
- if (readdirSync(target).length) throw new Stop(`${shown} already has files in it, and this command won't write over them. Name a new or empty folder.`)
45
- return true
46
- }
47
-
48
- // What the first run sent, and what the person does next, for each thing it can leave undone.
49
- const FIRST_RUN_TEXT = {
50
- none: () => ({
51
- state: `Pincast has your set, and the test person ${TEST_PERSON} holds Ferry Steps.`,
52
- next: 'Next, install it and start it:',
53
- }),
54
- collect: why => ({
55
- state: `Pincast has your set but didn't confirm the first collect (${why}). Your app is fine, and the commands below send it. Sending it again within a day changes nothing.`,
56
- next: 'Next, install it, send its one collect, and start it:',
57
- }),
58
- both: why => ({
59
- state: `Pincast didn't confirm your set (${why}). Your app is fine, and the commands below send the set and one collect.`,
60
- next: 'Next, install it, send its set and one collect, and start it:',
61
- }),
62
- }
63
-
64
- function successText({ shown, inPlace, id, claimUrl, endsOn, base, first }) {
65
- const envPath = inPlace ? '.env' : join(shown, '.env')
66
- const steps = [...(inPlace ? [] : [`cd ${shellWord(shown)}`]), 'npm ci', ...firstRunCommands(base, first.left), 'npm run dev']
67
- const { state, next } = FIRST_RUN_TEXT[first.left](first.why)
68
- return [
69
- `Your app is ready in ${inPlace ? 'this folder' : shown}, with the test app ${id}.`,
70
- '',
71
- `Its key is saved in ${envPath}. Only your account can read that file, and git ignores it.`,
72
- '',
73
- state,
74
- '',
75
- `To keep this app past ${endsOn}, open this link while signed in to Pincast:`,
76
- '',
77
- ` ${claimUrl}`,
78
- '',
79
- next,
80
- '',
81
- ...steps.map(s => ` ${s}`),
82
- '',
83
- 'Then open http://localhost:5173.',
84
- '',
85
- ].join('\n')
86
- }
1
+ // create-pincast is a shim from 0.2.0 on. The whole command, with its text and its exit codes, lives in
2
+ // @pincast/cli, whose `pincast init` runs the same code. This file gives it this package's name.
3
+ import { runCreate } from '@pincast/cli/init'
4
+ import { COMMAND, PACKAGE_NAME } from './name.js'
87
5
 
88
6
  /** Runs the command and answers its exit code. Nothing here prints an error's own message. */
89
- export async function run(argv, {
90
- env = process.env,
91
- cwd = process.cwd(),
92
- out = text => process.stdout.write(text),
93
- err = text => process.stderr.write(text),
94
- fetchImpl = fetch,
95
- beforeCopy = () => {},
96
- firstRunTimeoutMs = FIRST_RUN_TIMEOUT_MS,
97
- } = {}) {
98
- const say = text => out(hideKeys(text))
99
- const complain = text => err(`${hideKeys(text)}\n`)
100
- const stopper = new AbortController()
101
- const onInterrupt = () => stopper.abort()
102
- const firstRunStopper = new AbortController()
103
- const onFirstRunInterrupt = () => firstRunStopper.abort()
104
-
105
- let target
106
- const files = []
107
- let madeFrom
108
- let holdsApp = false
109
-
110
- try {
111
- const args = parseArgs(argv)
112
- if (args.help) {
113
- say(USAGE)
114
- return 0
115
- }
116
- const { base, custom } = apiBase(env)
117
- target = resolve(cwd, args.folder)
118
- const fromCwd = relative(cwd, target)
119
- const inPlace = fromCwd === ''
120
- const shown = inPlace ? basename(target) : (fromCwd.startsWith('..') || isAbsolute(fromCwd) ? target : fromCwd)
121
-
122
- if (!checkTarget(target, shown)) madeFrom = mkdirSync(target, { recursive: true })
123
-
124
- // The starter goes down first: a failed copy then costs no test app.
125
- beforeCopy()
126
- copyStarter(target, files)
127
-
128
- process.once('SIGINT', onInterrupt)
129
- const app = await makeTestApp(base, { fetchImpl, signal: stopper.signal })
130
- process.removeListener('SIGINT', onInterrupt)
131
- holdsApp = true
132
-
133
- try {
134
- writeEnv(target, { key: app.key, claimUrl: app.claimUrl, customBase: custom ? base : null })
135
- } catch (e) {
136
- throw new Stop(`Pincast made the test app, but its key couldn't be saved (${e?.code ?? 'write failed'}). Nobody holds that key now, so that app can't be used and it ends on its own. Run the command again in a new folder.`)
137
- }
138
- try {
139
- setAppId(target, app.id)
140
- } catch (e) {
141
- throw new Stop(`The key is saved in .env, but the app's id couldn't be written (${e?.code ?? 'write failed'}). Set APP.id in shared/app.js to ${app.id}, and run UPDATE_GOLDENS=1 npm test.`)
142
- }
143
-
144
- // From here the app exists and works, so nothing that goes wrong with these two calls stops the command.
145
- say('Sending the starter\'s set and one test collect to Pincast.\n\n')
146
- process.once('SIGINT', onFirstRunInterrupt)
147
- const first = await sendFirstRun(base, target, {
148
- appId: app.id,
149
- key: app.key,
150
- fetchImpl,
151
- stop: firstRunStopper.signal,
152
- timeoutMs: firstRunTimeoutMs,
153
- })
154
- process.removeListener('SIGINT', onFirstRunInterrupt)
155
-
156
- try {
157
- addReadmeSection(target, { id: app.id, base, endsOn: app.endsOn, left: first.left })
158
- } catch (e) {
159
- throw new Stop(`Your app is made and its key is in .env, but its README couldn't be updated (${e?.code ?? 'write failed'}). Skip the README's Go live steps, because the first one would erase the key, and follow https://docs.pincast.fm/quickstart. Your claim link is in .env as PINCAST_CLAIM_URL.`)
160
- }
161
-
162
- say(successText({ shown, inPlace, id: app.id, claimUrl: app.claimUrl, endsOn: app.endsOn, base, first }))
163
- return firstRunStopper.signal.aborted ? 130 : 0
164
- } catch (e) {
165
- process.removeListener('SIGINT', onInterrupt)
166
- process.removeListener('SIGINT', onFirstRunInterrupt)
167
- if (!holdsApp && target) {
168
- try {
169
- removeStarter(target, files, madeFrom)
170
- } catch { /* the message below still has to reach the person */ }
171
- }
172
- complain(e instanceof Stop ? e.message : `Something went wrong${e?.code ? ` (${e.code})` : ''}. No key was printed. Run the command again in a new or empty folder.`)
173
- return e instanceof Stop ? e.exitCode : 1
174
- }
175
- }
7
+ export const run = (argv, options = {}) => runCreate(argv, { command: COMMAND, userAgent: PACKAGE_NAME, ...options })
package/src/api.js DELETED
@@ -1,138 +0,0 @@
1
- import { PACKAGE_NAME } from './name.js'
2
-
3
- export const DEFAULT_API = 'https://api.pincast.fm/v1'
4
- export const API_ENV = 'PINCAST_CREATE_API'
5
- const TIMEOUT_MS = 30_000
6
-
7
- // What a good answer holds. These values land in a source file, in .env and on the terminal, so each
8
- // one has to match exactly before it's used.
9
- const APP_ID_RE = /^test-[a-z2-7]{10}$/
10
- const CLAIM_URL_RE = /^https:\/\/[a-z0-9.-]+(?::\d+)?\/[A-Za-z0-9/_-]*#code=pcc_[A-Za-z0-9_-]{43}$/
11
- const SAFE_BASE_RE = /^[A-Za-z0-9:/._[\]-]+$/
12
- const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
13
-
14
- // Failures that happen before the request leaves this machine, so no app can exist.
15
- const NEVER_SENT = new Set([
16
- 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT',
17
- 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN',
18
- 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'ERR_TLS_CERT_ALTNAME_INVALID',
19
- ])
20
-
21
- const ORPHAN = "If Pincast made a test app, nobody holds its key, so it can't be used and it ends on its own. Each call makes a new app, so this command won't call again by itself. Run it again when you're ready."
22
-
23
- /** A failure with a message written for the person at the terminal. */
24
- export class Stop extends Error {
25
- constructor(message, exitCode = 1) {
26
- super(message)
27
- this.exitCode = exitCode
28
- }
29
- }
30
-
31
- /** The API base: the default, or the override in PINCAST_CREATE_API, which tests use. */
32
- export function apiBase(env) {
33
- const raw = env[API_ENV]
34
- if (!raw) return { base: DEFAULT_API, custom: false }
35
- let url
36
- try {
37
- url = new URL(raw)
38
- } catch {
39
- throw new Stop(`${API_ENV} isn't a web address.`)
40
- }
41
- const allowed = url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname))
42
- if (!allowed) throw new Stop(`${API_ENV} has to use https, or http on this machine.`)
43
- const base = `${url.origin}${url.pathname}`.replace(/\/+$/, '')
44
- if (url.username || url.password || url.search || url.hash || !SAFE_BASE_RE.test(base)) {
45
- throw new Stop(`${API_ENV} has to be a plain address, such as https://example.org/v1.`)
46
- }
47
- return { base, custom: true }
48
- }
49
-
50
- /** Turns a Retry-After header into words. */
51
- export function waitText(header, now = Date.now()) {
52
- if (!header) return 'later'
53
- const value = header.trim()
54
- const seconds = /^\d+$/.test(value) ? Number(value) : (Date.parse(value) - now) / 1000
55
- if (!Number.isFinite(seconds) || seconds < 0) return 'later'
56
- if (seconds < 90) return 'in a minute or two'
57
- if (seconds < 5400) return `in about ${Math.ceil(seconds / 60)} minutes`
58
- return `in about ${Math.ceil(seconds / 3600)} hours`
59
- }
60
-
61
- const failureCode = (e) => e?.cause?.code ?? e?.code ?? e?.cause?.errors?.[0]?.code
62
-
63
- function errorCode(text) {
64
- try {
65
- const code = JSON.parse(text)?.data?.code
66
- return typeof code === 'string' ? code : null
67
- } catch {
68
- return null
69
- }
70
- }
71
-
72
- function refusal(status, text, retryAfter, base) {
73
- const code = errorCode(text)
74
- if (status === 429) {
75
- const wait = waitText(retryAfter)
76
- return code === 'test_apps_limit'
77
- ? new Stop(`Pincast has made all the test apps it makes in a day. Try again ${wait}.`)
78
- // The firewall's 429 carries no Retry-After, and its window is 10 minutes.
79
- : new Stop(`Too many test apps have come from this network. Try again ${wait === 'later' ? 'in 10 minutes' : wait}.`)
80
- }
81
- if (status === 403 && code === 'browser_not_allowed') {
82
- return new Stop('Pincast refused this call as one from a web page. This command sends no Origin header, so a proxy or network tool probably added it. Try again from a plain terminal.')
83
- }
84
- if (status === 404) return new Stop(`Pincast has no test app service at ${base}, so no test app was made.`)
85
- if (status >= 300 && status < 400) {
86
- return new Stop(`Pincast pointed this call at another address. This command didn't follow it, because a second call could make a second app. No key was saved. ${ORPHAN}`)
87
- }
88
- if (status >= 400 && status < 500) return new Stop(`Pincast refused the call (${status}), so no test app was made.`)
89
- return new Stop(`Pincast answered with an error (${status}), and no key was saved. ${ORPHAN}`)
90
- }
91
-
92
- /** Checks a 200's body. Never repeats any of it: a parse error's message can quote the key. */
93
- function readAnswer(text) {
94
- const unreadable = () => new Stop(`Pincast answered, but this command couldn't read the answer, so no key was saved. ${ORPHAN}`)
95
- let answer
96
- try {
97
- answer = JSON.parse(text)
98
- } catch {
99
- throw unreadable()
100
- }
101
- const id = answer?.app?.id
102
- const key = answer?.key
103
- const claimUrl = answer?.claim?.url
104
- const expiresAt = answer?.claim?.expiresAt ?? answer?.app?.expiresAt
105
- if (typeof id !== 'string' || !APP_ID_RE.test(id)) throw unreadable()
106
- if (typeof key !== 'string' || !key.startsWith(`pck_${id}_`) || !/^[A-Za-z0-9_-]{16,256}$/.test(key.slice(`pck_${id}_`.length))) throw unreadable()
107
- if (typeof claimUrl !== 'string' || !CLAIM_URL_RE.test(claimUrl)) throw unreadable()
108
- if (typeof expiresAt !== 'string' || !Number.isFinite(Date.parse(expiresAt))) throw unreadable()
109
- return { id, key, claimUrl, endsOn: new Date(expiresAt).toISOString().slice(0, 10) }
110
- }
111
-
112
- /**
113
- * Makes one test app with one POST: no body, no Origin, no redirect followed, and never a second call,
114
- * because each call that succeeds makes a new app.
115
- */
116
- export async function makeTestApp(base, { fetchImpl = fetch, signal } = {}) {
117
- const timeout = AbortSignal.timeout(TIMEOUT_MS)
118
- const combined = signal ? AbortSignal.any([timeout, signal]) : timeout
119
- let res
120
- let text
121
- try {
122
- res = await fetchImpl(`${base}/test-apps`, {
123
- method: 'POST',
124
- headers: { Accept: 'application/json', 'User-Agent': PACKAGE_NAME },
125
- redirect: 'manual',
126
- signal: combined,
127
- })
128
- text = await res.text()
129
- } catch (e) {
130
- if (signal?.aborted) throw new Stop(`Stopped before Pincast answered, so no key was saved. ${ORPHAN}`, 130)
131
- if (!res && NEVER_SENT.has(failureCode(e))) {
132
- throw new Stop(`Couldn't reach Pincast at ${base}, so no test app was made. Check your connection, then run the command again.`)
133
- }
134
- throw new Stop(`The call went out to Pincast, but its answer never arrived, so no key was saved. ${ORPHAN}`)
135
- }
136
- if (res.status !== 200) throw refusal(res.status, text, res.headers.get('retry-after'), base)
137
- return readAnswer(text)
138
- }
package/src/firstrun.js DELETED
@@ -1,83 +0,0 @@
1
- import { readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
3
- import { PACKAGE_NAME } from './name.js'
4
- import { COLLECT_RETRY_KEY, FIRST_COLLECT, SET_ID } from './starter.js'
5
-
6
- export const FIRST_RUN_TIMEOUT_MS = 15_000
7
-
8
- /**
9
- * One call with the app's key. Answers { ok: true } or { ok: false, why } and never throws, because a
10
- * failure here can't stop the command: the app is already made. `why` is written here and repeats no
11
- * part of the answer or of any error, either of which could quote the key. No redirect is followed,
12
- * because fetch would carry the key header to the new address.
13
- */
14
- async function send(url, { method, key, body, headers = {}, accept, fetchImpl, stop, timeoutMs }) {
15
- const timeout = AbortSignal.timeout(timeoutMs)
16
- try {
17
- const res = await fetchImpl(url, {
18
- method,
19
- headers: {
20
- Accept: 'application/json',
21
- 'Content-Type': 'application/json',
22
- 'User-Agent': PACKAGE_NAME,
23
- 'X-Pincast-Key': key,
24
- ...headers,
25
- },
26
- body,
27
- redirect: 'manual',
28
- signal: AbortSignal.any([timeout, stop]),
29
- })
30
- const text = await res.text()
31
- if (res.status !== 200) return { ok: false, why: `it answered ${res.status}` }
32
- let answer
33
- try {
34
- answer = JSON.parse(text)
35
- } catch {
36
- return { ok: false, why: "its answer couldn't be read" }
37
- }
38
- return accept(answer) ? { ok: true } : { ok: false, why: "its answer couldn't be read" }
39
- } catch {
40
- if (stop.aborted) return { ok: false, why: 'stopped' }
41
- if (timeout.aborted) {
42
- const seconds = Math.max(1, Math.round(timeoutMs / 1000))
43
- return { ok: false, why: `no answer in ${seconds} second${seconds === 1 ? '' : 's'}` }
44
- }
45
- return { ok: false, why: 'the connection failed' }
46
- }
47
- }
48
-
49
- /**
50
- * Sends the starter's set, then one collect for the test person, so the first screen shows a real card.
51
- * Answers what is still left to send: 'none', 'collect' or 'both', with the reason.
52
- *
53
- * The set goes first because a collect on a missing set is refused. Neither call is retried here.
54
- * - A repeat of the PUT is harmless: it upserts by set id and card key.
55
- * - A collect with no `at` counts again on each call, so this one carries an Idempotency-Key. If its
56
- * answer is lost, the printed command repeats the same key and body, and Pincast answers from the
57
- * first call for 24 hours instead of counting a second collect.
58
- */
59
- export async function sendFirstRun(base, target, { appId, key, fetchImpl = fetch, stop, timeoutMs = FIRST_RUN_TIMEOUT_MS }) {
60
- let setBody
61
- try {
62
- setBody = readFileSync(join(target, 'data', 'set.json'), 'utf8')
63
- } catch {
64
- return { left: 'both', why: "the set file couldn't be read" }
65
- }
66
- const common = { key, fetchImpl, stop, timeoutMs }
67
- const set = await send(`${base}/sets/${SET_ID}`, {
68
- ...common,
69
- method: 'PUT',
70
- body: setBody,
71
- accept: a => a?.app === appId && a?.set === SET_ID,
72
- })
73
- if (!set.ok) return { left: 'both', why: set.why }
74
- const collect = await send(`${base}/sets/${SET_ID}/collects`, {
75
- ...common,
76
- method: 'POST',
77
- headers: { 'Idempotency-Key': COLLECT_RETRY_KEY },
78
- body: JSON.stringify(FIRST_COLLECT),
79
- accept: a => a?.collected === true && a?.card?.key === FIRST_COLLECT.card,
80
- })
81
- if (!collect.ok) return { left: 'collect', why: collect.why }
82
- return { left: 'none' }
83
- }
package/src/starter.js DELETED
@@ -1,156 +0,0 @@
1
- import { constants, chmodSync, copyFileSync, mkdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
2
- import { dirname, join } from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
- import { COMMAND } from './name.js'
5
-
6
- const root = join(dirname(fileURLToPath(import.meta.url)), '..')
7
-
8
- // The starter's files and the commit they came from.
9
- export const manifest = JSON.parse(readFileSync(join(root, 'template.json'), 'utf8'))
10
-
11
- const STARTER_ID = 'lantern-walk'
12
- export const SET_ID = 'old-town-lanterns'
13
- export const TEST_PERSON = 'test_demo'
14
-
15
- // The one collect the command sends. The printed command repeats the same body and the same retry key,
16
- // so Pincast treats the two as one call for 24 hours, and a lost answer can't count a second collect.
17
- export const FIRST_COLLECT = { card: 'lantern:ferry-steps', actor: { id: TEST_PERSON, source: 'anonymous' } }
18
- export const COLLECT_RETRY_KEY = 'create-pincast-first-collect'
19
-
20
- // The example app's README predates test keys. template/ is rebuilt byte for byte from that repo, so a
21
- // fix made there would be lost at the next sync. Each new app's copy is corrected here instead. Once the
22
- // example drops the sentence, this replaces nothing.
23
- const OLD_KEY_LINE = 'Every Pincast key is live, so anything you write with one is real.'
24
- export const LIVE_KEY_LINE = 'A live key writes real data, and no API call deletes it.'
25
-
26
- // npm pack drops or rewrites these names, so the package stores them under another.
27
- const STORED = { '.gitignore': '_gitignore', '.env.example': '_env.example', 'package-lock.json': '_package-lock.json' }
28
- export const storedPath = file => join(root, 'template', STORED[file] ?? file)
29
-
30
- /**
31
- * Copies the starter into an empty folder. Refuses to replace any file. Each file joins `written` as
32
- * it lands, so a copy that fails partway can still be taken back.
33
- */
34
- export function copyStarter(target, written) {
35
- for (const file of Object.keys(manifest.files)) {
36
- const to = join(target, file)
37
- mkdirSync(dirname(to), { recursive: true })
38
- copyFileSync(storedPath(file), to, constants.COPYFILE_EXCL)
39
- written.push(file)
40
- }
41
- }
42
-
43
- /**
44
- * Takes back what copyStarter wrote. madeFrom is the highest folder this run made, if any: those
45
- * folders go too, unless something else is in them.
46
- */
47
- export function removeStarter(target, files, madeFrom) {
48
- for (const file of files) rmSync(join(target, file), { force: true })
49
- const folders = new Set()
50
- for (const file of Object.keys(manifest.files)) {
51
- for (let d = dirname(file); d !== '.'; d = dirname(d)) folders.add(d)
52
- }
53
- for (const d of [...folders].sort((a, b) => b.length - a.length)) {
54
- try {
55
- rmdirSync(join(target, d))
56
- } catch { /* missing, or something else is in it: leave it */ }
57
- }
58
- if (!madeFrom) return
59
- for (let d = target; d.length >= madeFrom.length; d = dirname(d)) {
60
- try {
61
- rmdirSync(d)
62
- } catch {
63
- return
64
- }
65
- if (d === madeFrom) return
66
- }
67
- }
68
-
69
- /** Writes .env, readable only by this account. The claim link is quoted because it holds a #. */
70
- export function writeEnv(target, { key, claimUrl, customBase }) {
71
- const lines = [
72
- `# Made by ${COMMAND}. This file holds your test key, so keep it private.`,
73
- `PINCAST_KEY=${key}`,
74
- `PINCAST_ACTOR=${TEST_PERSON}`,
75
- `PINCAST_CLAIM_URL="${claimUrl}"`,
76
- ]
77
- if (customBase) lines.push(`PINCAST_API=${customBase}`)
78
- const path = join(target, '.env')
79
- writeFileSync(path, `${lines.join('\n')}\n`, { flag: 'wx', mode: 0o600 })
80
- chmodSync(path, 0o600)
81
- }
82
-
83
- /** Puts the app's id in shared/app.js and in the goldens, which draw it into every card's data-id. */
84
- export function setAppId(target, id) {
85
- const appFile = join(target, 'shared', 'app.js')
86
- const source = readFileSync(appFile, 'utf8')
87
- const line = `{ id: '${STARTER_ID}',`
88
- if (source.split(line).length !== 2) throw new Error('app id line not found')
89
- writeFileSync(appFile, source.replace(line, `{ id: '${id}',`))
90
- for (const file of Object.keys(manifest.files)) {
91
- if (!/^test\/goldens\/.+\.html$/.test(file)) continue
92
- const path = join(target, file)
93
- writeFileSync(path, readFileSync(path, 'utf8').replaceAll(`data-id="${STARTER_ID}:`, `data-id="${id}:`))
94
- }
95
- }
96
-
97
- /**
98
- * The commands that send what the first run still needs, as printed and as written in the README.
99
- * left is 'both', 'collect' or 'none'. After a collect that may have landed ('collect'), the command
100
- * carries the retry key, so running it can't count a second collect.
101
- */
102
- export function firstRunCommands(base, left = 'both') {
103
- if (left === 'none') return []
104
- const put = [
105
- `curl -X PUT ${base}/sets/${SET_ID} \\`,
106
- ' -H "X-Pincast-Key: $PINCAST_KEY" \\',
107
- ' -H "Content-Type: application/json" \\',
108
- ' -d @data/set.json',
109
- ]
110
- const collect = [
111
- `curl -X POST ${base}/sets/${SET_ID}/collects \\`,
112
- ' -H "X-Pincast-Key: $PINCAST_KEY" \\',
113
- ' -H "Content-Type: application/json" \\',
114
- ...(left === 'collect' ? [` -H "Idempotency-Key: ${COLLECT_RETRY_KEY}" \\`] : []),
115
- ` -d '{ "card": "${FIRST_COLLECT.card}", "actor": { "id": "${TEST_PERSON}", "source": "anonymous" } }'`,
116
- ]
117
- return ['set -a; . ./.env; set +a', ...(left === 'collect' ? [] : put), ...collect]
118
- }
119
-
120
- const README_LEAD = {
121
- none: `This app's set and one collect for \`${TEST_PERSON}\` are already on Pincast. To see them, install the app and start it:`,
122
- collect: "This app's set is on Pincast. To see live cards, install the app, send its one collect, then start it:",
123
- both: 'To see live cards, install the app, send its set and one collect, then start it:',
124
- }
125
-
126
- /**
127
- * Adds this copy's own section to its README, saying what the first run left to do. The starter's Go
128
- * live steps open by replacing .env, which here would erase the key. The claim link stays out, because
129
- * a README gets committed.
130
- */
131
- export function addReadmeSection(target, { id, base, endsOn, left = 'both' }) {
132
- const path = join(target, 'README.md')
133
- const readme = readFileSync(path, 'utf8').replace(OLD_KEY_LINE, () => LIVE_KEY_LINE)
134
- const anchor = '## Run it\n'
135
- if (readme.split(anchor).length !== 2) throw new Error('README anchor not found')
136
- const section = [
137
- '## Your test app',
138
- '',
139
- `\`${COMMAND}\` made this copy and the test app \`${id}\` for it. The key and the claim link are in \`.env\`, which git ignores. A test key writes only to this app, and only for test people, whose ids start with \`test_\`.`,
140
- '',
141
- README_LEAD[left],
142
- '',
143
- '```sh',
144
- 'npm ci',
145
- ...firstRunCommands(base, left),
146
- 'npm run dev',
147
- '```',
148
- '',
149
- `The app ends on ${endsOn} unless you claim it. To keep it, open the \`PINCAST_CLAIM_URL\` from \`.env\` while signed in to Pincast.`,
150
- '',
151
- 'Save the Go live section below for when you have a live key. Its first step replaces `.env`, which would erase this key.',
152
- '',
153
- '',
154
- ].join('\n')
155
- writeFileSync(path, readme.replace(anchor, () => section + anchor))
156
- }
package/template/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Pincast, Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.